This article introduces a new way of uploading pictures, using HTML5 filereader to read picture files, and then transfer data to the server and then use PHP to process. The implementation process is as follows (with the picture preview feature)
Front end HTML code upload,html
Style as shown below
Next is the JS code
<script type= "Text/javascript" > $ (". UpButton"). Click (function () {//define the image format allowed to upload can be directly judged in the foreground, the illegal format will not upload Var
filetype = [' jpg ', ' jpeg ', ' png ', ' gif ']; if ($ ('. Image '). Get (0). files) {fi = $ ('. Image '). (0). Files[0];//obtain file information//Determine if file format is picture if not picture return false VA
R fname = Fi.name.split ('. ');
if (Filetype.indexof (fname[1].tolowercase ()) = = 1) {alert (' file format not supported ');
return;
}//Instantiate h5 filereader var fr = new FileReader (); Fr.readasdataurl (FI); Read the picture file in base64 encoding fr.onload = function (Frev) {pic = Frev.target.result;//Get Results data//start uploading before previewing picture $ ('.
Image_thumb '). attr (' src ', pic); Use AJAX to submit data using post methods $.post (' handle.php ', {message:pic, filename:f Name[0], filetype:fname[1], filesize:fi.size}, function (data) {DA
Ta = eval (' (' +data+ ') '); if (Data.code = 1 | | data.code = 2) {conSole.log (' upload failed ')}else if (data.code = 0) {console.log (' upload succeeded ')}}
);
}}) </script>
Next is the PHP processing code handle.php
$imgtype = Array (
' gif ' => ' gif ',
' png ' => ' png ',
' jpg ' => ' jpeg ',
' jpeg ' => ' jpeg '
); Picture type in the transmission process corresponding header information
$message = $_post[' message '];//Receive Base64 encoded picture data
$filename = $_post[' filename '];//Receive file name
$ftype = $_post[' filetype '];//Receive file type
//First remove the header information and then decode the remaining base64 encoded data
$message = Base64_decode (substr ($ Message,strlen (' data:image/'. $imgtype [Strtolower ($ftype)]. Base64, '));
$filename = $filename. ". $ftype;
$furl = "d:/now/";
Start writing
the file $file = fopen ($furl. $filename, "w");
if (fwrite ($file, $message) = = False) {
echo json_encode (Array (' Code ' =>1, ' con ' => ' failed '));
Exit;
}
echo json_encode (Array (' Code ' =>0, ' con ' => $filename));
Select the file and click on the upload effect as shown below
The above is the entire picture upload code. Of course, there are many parts of PHP can be optimized, such as the file name part, can be renamed to ensure that the same file name uploaded after the file name is different and so on. This upload way I am also just beginning to use, originally was by node.js do upload of inspiration, and then try to apply to PHP, did not expect to upload successfully.
I hope you can also follow this method to achieve picture upload.