Use the ajaxfileupload plug-in to asynchronously upload and save images,

Source: Internet
Author: User

Use the ajaxfileupload plug-in to asynchronously upload and save images,

You can use the jquery plug-in ajaxfileupload. js to upload image files without refreshing pages. You can use the background management function to upload images, which is very convenient.

I. Target results:
1. When multiple images are uploaded to the front-end and the page is uploaded to the server, the page displays the image immediately without refreshing the new page.
2. In the background, images POST on the page are renamed and saved to the server.

Ii. Ideas:
1. encapsulate a js function uploadimg (imgid, fileid, hiddenid), which calls ajaxfileupload. js functions $. ajaxFileUpload () uploads the file ajax in the input type = 'file' label to the server. After the file is uploaded successfully, the system receives the json data returned. path, which is assigned to the img label and the corresponding hidden domain
2. on the server side, there is a PHP file specially used to process ajax upload images. First, determine whether the file type and size are valid, rename the file, and move a file temporary storage area, then return the image path to the front-end page in json format.
3. When the page actually submits the form information to the background for saving, the background moves the images in the temporary storage area to the folder where the images are permanently saved Based on the image PATH value in the hidden field.

Iii. Code:
1. Front-end:
① Html page:

② Uploadimg. js code, which calls the ajaxfileupload. js function to upload ajax image files and control the front-end page display after receiving the returned values.

Function uploadimg (imgid, fileid, hiddenid) {// imgid indicates the  tag id, and fileid indicates the id of the <input type = 'file'/> file Upload tag, hiddenid indicates the id of the hidden domain tag $ ("#" + imgid ). attr ("src", "/assets/img/loading/load.gif "). removeClass ("load0"); // load the loading image $. ajaxFileUpload ({url: 'http: // 127.0.0.1/common/upImgfile. php ', secureuri: false, fileElementId: fileid, ype: 'json', success: function (data, status) {// data content is customized in the background php code, json If (typeof (data. error )! = 'Undefined') {// File Upload error var error_msg = ""; switch (data. error) {case "101": error_msg = "file type error"; break; case "102": error_msg = "file too large"; break; case "400 ": error_msg = "illegal upload"; break; case "404": error_msg = "file blank"; break; default: error_msg = "server unstable ";} alert (error_msg);} else {$ ("#" + imgid ). attr ("src", data. path ). addClass ("load1"); // load the returned image path and append the style $ ("#" + hiddenid ). val (data. path); // assign values to the corresponding hidden fields so that they can be submitted to the backend. }}, error: function (data, status, e) {alert (e );}})}

2. Background:
UpImgfile. php code:

<? Php // receives FILES uploaded in POST mode and stores them in the Temporary Folder if (isset ($ _ FILES )&&(! Empty ($ _ FILES) {foreach ($ _ FILES as $ el) // gets FILES. By default, each file is uploaded by a single upload. {$ file = $ el ;} if (is_uploaded_file ($ file ["tmp_name"]) {// confirm that the file is uploaded in POST mode $ cache_path = ".. /assets/uploads/cache/"; // directory of the temporary file $ fname = $ file [" name "]; // get the file name $ ftype = $ file ["type"]; // get the file type $ ftmp_name = $ file ["tmp_name"]; // get the temporary file path $ fsize = $ file ["size"]; // get the file size $ ferror = $ file ["error"]; // get the file error code // determine whether the file size meets the Rule if (! Check_size ($ fsize) {echo json_encode (array ("error" => "102"); // The error code 102 indicates that the file is too large to exit ;} $ suffix = strtolower (stristr ($ fname ,". "); // get the file suffix (including the DoT number), and the suffix is lowercase // determine whether the file type is an image if (! Is_img ($ suffix) {// if it is not of the image type, the error 101 is returned, indicating the file type error echo json_encode (array ("error" => "101 ")); exit;} $ uniqStr = uniqid (strtotime ("now "). "_". mt_rand (100000,999999 ). "_"); // create a random ID $ fname_new = $ cache_path. $ uniqStr. $ suffix; // use the current timestamp to construct the new file name move_uploaded_file ($ ftmp_name, $ fname_new ); // move the files in the temporary file area to the temporary file area $ fname_new = stristr ($ fname_new, "/"); echo json_encode (array ("path" => $ fname_new )); // return the file path to the viewing client} else {echo json_encode (array ("error" => "400 ")); // error code 400 indicates Illegal File Upload (not submitted by httppost)} else {echo json_encode (array ("error" => "404 ")); // The Error Code 404 indicates that the file is empty}/*** determines whether the file suffix is an image * @ param string $ suffix: The suffixed name (for example, .jpg) * @ return bool returns true if it is an image suffix, otherwise, false */function is_img ($ suffix) {comment ') is returned; return in_array (strtolower ($ suffix), $ suffix_arr );} /*** determine whether the file size is invalid * @ param int $ size: an integer in bytes. The object size * @ return bool returns true if the file size is smaller than or equal to the specified maximum value, otherwise, false */function check_size ($ size) {$ postMaxSize = intval (ini_get ("post_max_size") is returned ")); // maximum value of post files $ uploadMaxFilesize = intval (ini_get ("upload_max_filesize"); // maximum value of upload uploaded files $ max = min ($ postMaxSize, $ uploadMaxFilesize) * 1024*1024; // convert MB to byte unit data if (intval ($ size) <= $ max) {return true ;}else {return false ;}}

IV,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.