JQuery AjaxUpload uploads image code,

Source: Internet
Author: User
Tags php file upload php website

JQuery AjaxUpload uploads image code,

The use of AJAXUPLOAD as the upload client without upload plug-in, its latest version is 3.9, the official address: http://valums.com/ajax-upload/

Introduce jquery. min.1.4.2.js and ajaxupload. js to the page.

<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script><script src="Scripts/ajaxupload3.9.js" type="text/javascript"></script>

HTML code:

<Style type = "text/css"> # txtFileName {width: 300px ;}. btnsubmit {border-bottom: # cc4f00 1px solid; border-left: # ff9000 1px solid; border-top: # ff9000 1px solid; border-right: # cc4f00 1px solid; text-align: center; padding: 2px 10px; line-height: 16px; background: # e36b0f; height: 24px; color: # fff; font-size: 12px; cursor: pointer ;}</style> upload image: <input type = "text" id = "txtFileName"/> <div id = "btnUp" style = "width: 300px; "class = btnsubmit> browse </div> <div id =" imglist "> </div>

Js Code Generation:

<Script type = "text/javascript"> $ (function () {var button = $ ('# btnUp'), interval; new AjaxUpload (button, {// action: 'upload-test. php ', the address action executed by the file upload server:'/handler/AjaxuploadHandler. ashx ', name: 'myfile', onSubmit: function (file, ext) {if (! (Ext &/^ (jpg | jpeg | JPG | JPEG) $/. test (ext) {alert ('the image format is incorrect. Select a jpg file! ', 'System prompt'); return false;} // change button text, when user selects filebutton. text ('uploading'); // If you want to allow uploading only 1 file at time, // you can disable upload buttonthis. disable (); // Uploding-> Uploading. -> Uploading... interval = window. setInterval (function () {var text = button. text (); if (text. length <10) {button. text (text + '|');} else {button. text ('uploading ') ;}}, 200) ;}, onComplete: funct Ion (file, response) {// file local file name, response server side returned information button. text ('upload an image (only JPG images can be uploaded, And the size cannot exceed 150 KB) '); window. clearInterval (interval); // enable upload buttonthis. enable (); var k = response. replace ("<PRE> ",""). replace ("</PRE>", ""); if (k = '-1') {alert ('your uploaded file is too large! Please do not exceed 150k');} else {alert ("the string returned by the server:" + k); alert ("local file name:" + file ); $ ("# txtFileName "). val (k); $ (" "). appendTo ($ ('# imglist ')). attr ("src", k) ;}}) ;}); </script>

Server-side ajaxuploadhandler. ashx code

Public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; HttpPostedFile postedFile = context. request. files [0]; string savePath = "/upload/images/"; int filelength = postedFile. contentLength; int fileSize = 163600; // 150 Kstring fileName = "-1"; // The returned uploaded file name if (filelength <= fileSize) {byte [] buffer = new byte [filelength]; postedFile. inputStream. read (buffer, 0, filelengt H); fileName = UploadImage (buffer, savePath, "jpg");} context. response. write (fileName);} public static string UploadImage (byte [] imgBuffer, string uploadpath, string ext) {try {System. IO. memoryStream m = new MemoryStream (imgBuffer); if (! Directory. exists (HttpContext. current. server. mapPath (uploadpath) Directory. createDirectory (HttpContext. current. server. mapPath (uploadpath); string imgname = CreateIDCode () + ". "+ ext; string _ path = HttpContext. current. server. mapPath (uploadpath) + imgname; Image img = Image. fromStream (m); if (ext = "jpg") img. save (_ path, System. drawing. imaging. imageFormat. jpeg); elseimg. save (_ path, System. drawing. imaging. imageFormat. gif); m. close (); return uploadpath + imgname;} catch (Exception ex) {return ex. message ;}} public static string CreateIDCode () {DateTime Time1 = DateTime. now. toUniversalTime (); DateTime Time2 = Convert. toDateTime ("1970-01-01"); TimeSpan span = Time1-Time2; // span is the difference between two dates string t = span. totalMilliseconds. toString ("0"); return t ;}

In PHP website development, the file upload function is often used. I have previously introduced how to use PHP to upload files. With the development of WEB technology, user experience has become the key to measuring the success of a website. Today we will share with you an example of how to use Jquery to implement the Ajax file upload function in PHP, the Jquery plug-in Ajaxupload is used to upload a single file and multiple files.

AjaxUpload

The Jquery plug-in AjaxUpload allows you to upload files in Ajax mode without creating a form. You can also create a form as needed.

Preparations

1. Download The Jquery Development Kit and file upload plug-in AjaxUpload.

2. Create uploadfile.html and introduce the Jquery Development Kit and AjaxUpload plug-in.

<script src="js/jquery-1.3.js"></script><script src="js/ajaxupload.3.5.js"></script> 

3. Create a DIV that triggers the Ajax file upload function according to the requirements of the Jquery plug-in AjaxUpload.

<Ul> <li id = "example"> <div id = "upload_button"> File Upload </div> <p> List of uploaded files: </p> <ol class = "files"> </ol> </ul>

Note: The following Code shows that the Jquery plug-in AjaxUpload triggers the file upload function based on the DIV of upload_button.

Front-end JS Code

In the code, I set the switch to match the upload file type as needed. You can also set whether to upload a single file or multiple files in Ajax mode.

$ (Document ). ready (function () {var button = $ ('# upload_button'), interval; var fileType = "all", fileNum = "one"; new AjaxUpload (button, {action: 'Do/uploadfile. php',/* data: {'buttoninfo': button. text ()}, */name: 'userfile', onSubmit: function (file, ext) {if (fileType = "pic ") {if (ext &/^ (jpg | png | jpeg | gif) $ /. test (ext) {this. setData ({'info': 'file type is image '});} else {$ (' <li> </li> '). appendTo ('# example. files '). te Xt ('non-image type file, re-upload '); return false ;}} button. text ('file uploading '); if (fileNum = 'one') this. disable (); interval = window. setInterval (function () {var text = button. text (); if (text. length <14) {button. text (text + '. ');} else {button. text ('file uploading '); }}, 200) ;}, onComplete: function (file, response) {if (response! = "Success") alert (response); button. text ('file upload'); window. clearInterval (interval); this. enable (); if (response = "success"); $ ('<li> </li> '). appendTo ('# example. files '). text (file );}});});

Note:

Row 1st: $ (document ). ready () function, a function in Jquery, similar to window. load: this function can be used to call the bound function immediately when the DOM is ready to read and manipulate.

Row 3rd: The fileType and fileNum parameters represent the type and quantity of files to be uploaded. The default value is to upload all types of files. Only one file can be uploaded at a time. For example, if you want to upload an image file or multiple files at a time, you can change the values of these two variables to pic and more.

6th ~ Row 8: POST Data to the server. You can set static values or obtain some dynamic values through the Jquery DOM operation function, such as the INPUT values in the form.

Row 3: equivalent to the frontend

<input type="file" name="userfile"> 

Server $ _ FILES ['userfile']

10th ~ Row 36: Functions triggered before file upload.

11th ~ Row 21: filters image files. Jquery setData is used to set the value of POST to the server.

25th ~ Row 26: sets whether to upload only one file or multiple files at the same time. If only one file is uploaded, the trigger button is disabled. If you want to transfer more files, set the MAXSIZE value in the server-side PHP File Upload program. Of course, the size limit of the uploaded files is also related to the settings in the PHP. ini file.

28th ~ Row 35: the text of the button is dynamically updated every 200 milliseconds during the File Upload process, and the prompt effect has been achieved. The window. setInterval function is used to execute a built-in function at a specified time. The interaction time is measured in seconds.

37th ~ Row 49: this function is triggered after the file upload function is complete. If an error is reported on the server based on the returned value, the front-end prompts an error through ALERT.

PHP file upload code on the server

This is basically based on the code example tutorial of the PHP file upload function introduced earlier. The file upload size settings and error information are described in detail in this article.

$ Upload_dir = '.. /file/'; $ file_path = $ upload_dir. $ _ FILES ['userfile'] ['name']; $ MAX_SIZE = 20000000; echo $ _ POST ['buttoninfo']; if (! Is_dir ($ upload_dir) {if (! Mkdir ($ upload_dir) echo "the File Upload directory does not exist and the file upload directory cannot be created"; if (! Chmod ($ upload_dir, 0755) echo "the permission of the file upload directory cannot be set to readable or writable ";} if ($ _ FILES ['userfile'] ['SIZE']> $ MAX_SIZE) echo "the size of the uploaded file exceeds the specified size "; if ($ _ FILES ['userfile'] ['SIZE'] = 0) echo "select the uploaded file"; if (! Move_uploaded_file ($ _ FILES ['userfile'] ['tmp _ name'], $ file_path) echo "failed to copy the file. please upload it again "; switch ($ _ FILES ['userfile'] ['error']) {case 0: echo "success"; break; case 1: echo "the uploaded file exceeds php. value restricted by the upload_max_filesize option in ini "; break; case 2: echo" the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form "; break; case 3: echo "only part of the file is uploaded"; break; case 4: echo "no file is uploaded"; break ;}

Summary

Basically, the frontend Ajax File Upload trigger function and the prototype of the server-side PHP file upload function have been introduced. You can add the front-end and back-end code as needed, you can also separate some functions, such as the file type, single file, or multi-file upload function. In general, it is easier to use the Jquery plug-in AjaxUpload to implement the file upload function.

Articles you may be interested in:
  • Jquery plugin ajaxupload for File Upload

Related Article

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.