The example code of the Ajax function to preview images before uploading,

Source: Internet
Author: User

The example code of the Ajax function to preview images before uploading,

Several small projects at hand use easyUI. At the beginning, the decision to use easyUI is doomed to separate the entire project from the front and back ends. Basically, all requests are completed using Ajax. When uploading a file, I used Ajax to upload the file and preview the image before uploading it. These two problems were solved and shared with my friends.

Preview before uploading

Method 1

Let's talk about the preview problem before the image is uploaded. Here we mainly use the FileReader object in html5. for more information about the FileReader object, see the FileReader interface learned in html5. Let's take a look at the implementation method:

<! DOCTYPE html> 

Here, FileReader is directly used for browsers that support FileReader. browsers that do not support FileReader are implemented using Microsoft filters (note that the onchange function is set for the input tag of image uploading ).

The implementation result is as follows:

Method 2

In addition to this method, we can also use a jQuery implementation method available on the Internet. For more information, see.

However, because the original version is too old, $ is used in it. browser. msie is removed from jQuery1.9, so if we want to use this, we need to do some additional processing. the js file content is as follows:

JQuery. browser = {}; (function () {jQuery. browser. msie = false; jQuery. browser. version = 0; if (navigator. userAgent. match (/MSIE ([0-9] + ). /) {jQuery. browser. msie = true; jQuery. browser. version = RegExp. $1 ;}}) (); jQuery. fn. extend ({uploadPreview: function (opts) {var _ self = this, _ this = $ (this); opts = jQuery. extend ({Img: "ImgPr", Width: 100, Height: 100, ImgType: ["gif", "jpeg", "jpg", "bmp ", "png"], Callback: Function () {}}, opts ||{}); _ self. getObjectURL = function (file) {var url = null; if (window. createObjectURL! = Undefined) {url = window. createObjectURL (file)} else if (window. URL! = Undefined) {url = window. URL. createObjectURL (file)} else if (window. webkitURL! = Undefined) {url = window. webkitURL. createObjectURL (file)} return url}; _ this. change (function () {if (this. value) {if (! RegExp ("\. ("+ opts. imgType. join ("|") + ") $", "I "). test (this. value. toLowerCase () {alert ("file selection error, image type must be" + opts. imgType. join (",") + "); this. value = ""; return false} if ($. browser. msie) {try {$ ("#" + opts. img ). attr ('src', _ self. getObjectURL (this. files [0])} catch (e) {var src = ""; var obj = $ ("#" + opts. img); var div = obj. parent ("div") [0]; _ self. select (); if (top! = Self) {your own parent.doc ument. body. focus ()} else {_ self. blur ()} src = document. selection. createRange (). text; document. selection. empty (); obj. hide (); obj. parent ("div" ).css ({'filter': 'progid: DXImageTransform. microsoft. alphaImageLoader (sizingMethod = scale) ', 'width': opts. width + 'px ', 'height': opts. height + 'px '}); div. filters. item ("DXImageTransform. microsoft. alphaImageLoader "). src = src} else {$ ("#" + opts. img ). attr ('src', _ self. getObjectURL (this. files [0])} opts. callback ()}})}});

Then introduce this js file to our html file:

<! DOCTYPE html> 

Note the following points:

1. Introduce the custom uploadPreview. js file to the HTML page.

2. Pre-define the img label for displaying the preview image. The label must have an id.

3. Find the img tag and call the uploadPreview function.

The execution result is as follows:

Upload image files using Ajax

It is easy to upload image files using Ajax. The core code is as follows:

 var formData = new FormData();  formData.append("username", $("#username").val());  formData.append("file", $("#userface")[0].files[0]);  $.ajax({   url: '/fileupload',   type: 'post',   data: formData,   processData: false,   contentType: false,   success: function (msg) {    alert(msg);   }  });

The core is to define a FormData object and encapsulate the data to be uploaded into this object. Then, when ajax uploads data, set the data attribute to formdata, and set the processData attribute to false, indicating that jquery does not process the sent data, and set the contentType attribute to false, do not set the contentType attribute of the request header. OK, mainly set these three items. After the setting is successful, the other processing will be consistent with the regular ajax usage.

You can download the background processing code from the case at the end of the article. I won't show it here.

Source code download: http://xiazai.jb51.net/201707/yuanma/AjaxFileUpload.rar

Summary

The above is the example code of the Ajax upload function and the preview function before uploading. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.