Home >Web Front-end >JS Tutorial >jQuery AjaxUpload upload image code_jquery
This time, AJAXUPLOAD is used as the upload client brushless 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 into 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> 上传图片:<input type="text" id="txtFileName" /><div id="btnUp" style="width:300px;" class=btnsubmit >浏览</div> <div id="imglist"></div>
js code:
<script type="text/javascript"> $(function () { var button = $('#btnUp'), interval; new AjaxUpload(button, { //action: 'upload-test.php',文件上传服务器端执行的地址 action: '/handler/AjaxuploadHandler.ashx', name: 'myfile', onSubmit: function (file, ext) { if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) { alert('图片格式不正确,请选择 jpg 格式的文件!', '系统提示'); return false; } // change button text, when user selects file button.text('上传中'); // If you want to allow uploading only 1 file at time, // you can disable upload button this.disable(); // Uploding -> Uploading. -> Uploading... interval = window.setInterval(function () { var text = button.text(); if (text.length < 10) { button.text(text + '|'); } else { button.text('上传中'); } }, 200); }, onComplete: function (file, response) { //file 本地文件名称,response 服务器端传回的信息 button.text('上传图片(只允许上传JPG格式的图片,大小不得大于150K)'); window.clearInterval(interval); // enable upload button this.enable(); var k = response.replace("<PRE>", "").replace("", ""); if (k == '-1') { alert('您上传的文件太大啦!请不要超过150K'); } else { alert("服务器端传回的串:"+k); alert("本地文件名称:"+file); $("#txtFileName").val(k); $("").appendTo($('#imglist')).attr("src", k); } } }); });
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; //150K string fileName = "-1"; //返回的上传后的文件名 if (filelength <= fileSize) { byte[] buffer = new byte[filelength]; postedFile.InputStream.Read(buffer, 0, filelength); 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); else img.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就是两个日期之间的差额 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 implement the file upload function. With the development of WEB technology, user experience has become the key to measuring the success of a website. Today I 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, which can implement a single file and Multiple file upload function.
AjaxUpload
When the Jquery plug-in AjaxUpload implements the file upload function, there is no need to create a form form. It can realize file upload in Ajax mode. Of course, you can also create a form form as needed.
Preparation
1. Download the Jquery development package and file upload plug-in AjaxUpload.
2. Create uploadfile.html and introduce the Jquery development package and AjaxUpload plug-in
<script src="js/jquery-1.3.js"></script> <script src="js/ajaxupload.3.5.js"></script>
3. According to the needs of the Jquery plug-in AjaxUpload, create a DIV that triggers the Ajax file upload function
<ul> <li id="example"> <div id="upload_button">文件上传</div> <p>已上传的文件列表:</p> <ol class="files"></ol> </ul>
Note: From the code below, we can see that the Jquery plug-in AjaxUpload triggers the file upload function based on the upload_button DIV.
Front-end JS code
I set a switch in the code to match the uploaded file type as needed, and 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': '文件类型为图片' }); } else { $('<li></li>').appendTo('#example .files').text('非图片类型文件,请重传'); return false; } } button.text('文件上传中'); if(fileNum == 'one') this.disable(); interval = window.setInterval(function(){ var text = button.text(); if (text.length < 14){ button.text(text + '.'); } else { button.text('文件上传中'); } }, 200); }, onComplete: function(file, response){ if(response != "success") alert(response); button.text('文件上传'); window.clearInterval(interval); this.enable(); if(response == "success"); $('<li></li>').appendTo('#example .files').text(file); } }); });
Note:
Line 1: $(document).ready() function, a function in Jquery, similar to window.load. Use this function to call the bound function immediately when the DOM is loaded and ready to be read and manipulated.
Line 3: The fileType and fileNum parameters represent the type and number of uploaded files. The default value is that all types of files can be uploaded. Only one file can be uploaded at the same time. If you want to upload image files or multiple files at the same time, you can The values of these two variables become pic and more.
Lines 6~8: POST data to the server. You can set static values or obtain some dynamic values through Jquery's DOM operation function, such as the value of INPUT in the form, etc.
Line 9: Equivalent to frontend
<input type="file" name="userfile">
Server-side $_FILES['userfile']
Line 10~36: Function triggered before file upload.
Line 11~21: Filtering function of image file type, Jquery setData function is used to set the value of POST to the server.
Lines 25~26: Set whether to upload only one file or multiple files at the same time. If only one file is uploaded, the trigger button will be disabled. If you want to transfer several more files, please set the value of MAXSIZE in the server-side PHP file upload program. Of course, the size limit of uploaded files is also related to the settings in the PHP.INI file.
Lines 28~35: During the file upload process, the text of the button is dynamically updated every 200 milliseconds, achieving the effect of dynamic prompts. The window.setInterval function is used to execute the built-in function every specified time. The interaction time unit is milliseconds.
Lines 37~49: The function is triggered after the file upload function is completed. If the server reports an error according to the return value, the front-end prompts the error message through ALERT.
Server-side PHP file upload code
It is generally adapted based on the PHP file upload function code example tutorial introduced before. The settings of the file upload size, error messages and other instructions involved have been explained 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 "文件上传目录不存在并且无法创建文件上传目录"; if(!chmod($upload_dir,0755)) echo "文件上传目录的权限无法设定为可读可写"; } if($_FILES['userfile']['size']>$MAX_SIZE) echo "上传的文件大小超过了规定大小"; if($_FILES['userfile']['size'] == 0) echo "请选择上传的文件"; if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path)) echo "复制文件失败,请重新上传"; switch($_FILES['userfile']['error']) { case 0: echo "success" ; break; case 1: echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值"; break; case 2: echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值"; break; case 3: echo "文件只有部分被上传"; break; case 4: echo "没有文件被上传"; break; }
Summary
Basically, the prototypes of the front-end Ajax file upload trigger function and the server-side PHP file upload function have been introduced. You can supplement the front-end and back-end codes according to your own needs, or you can separate some functions, such as file type, single File or multiple file upload function. In general, it is relatively easy to apply the Jquery plug-in AjaxUpload to implement the file upload function.