How to implement Ajax upload image and preview function

Source: Internet
Author: User
Several small projects have recently been used in Easyui, and at the outset the decision to use Easyui was destined to separate the project as a whole, and basically all of the requests were done using AJAX. In the file upload the use of the Ajax upload files, as well as the image before uploading the preview effect, solve the two small problems, and the small partners to share, hope to help everyone.

Pre-upload Preview

Way One

First of all, the preview problem before uploading the picture. Here the main use of HTML5 in the FileReader object to achieve, about FileReader objects, if small partners do not understand, you can view this article HTML5 learning FileReader interface. Let's take a look at the implementation method:

<! DOCTYPE html>

This is true for browsers that support FileReader, and browsers that do not support FileReader are implemented using Microsoft Filters (Note the onchange function for the input tag of the image upload).

The implementation results are as follows:

Way Two

In addition to this approach, we can adopt a jquery-ready approach on the web. Here is the main reference here.

However, because the original text age, inside the use of the $.browser.msie from the jQuery1.9 was removed, so if we want to use this to do a little extra processing, my modified Uploadpreview.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, and _this = $ (this); opts = Jquery.extend ({Img: "IMGPR", width:100, height:100, Imgtype: ["gif", "JPEG", "JPG", "BMP", "PNG"], Cal Lback: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 ("Select File error, picture type must be" + opts.     Imgtype.join (",") + "one of the"); 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 p = obj.parent ("P") [0];      _self.select (); if (top! = self) {window.parent.document.body.focus ()} else {_self.blur ()} src = Document.s      Election.createrange (). text;      Document.selection.empty ();      Obj.hide (); Obj.parent ("P"). css ({' Filter ': ' Progid:DXImageTransform.Microsoft.AlphaImageLoader (Sizingmethod=scale) ', ' wid Th ': OPTs. Width + ' px ', ' height ': opts.      Height + ' px '}); P.filters.item ("DXImageTransform.Microsoft.AlphaImageLoader"). src = src}} else {$ ("#" + opts. IMG). attr (' src ', _self.getobjecturl (this.files[0))} opts. Callback ()})});

The

Then introduces this JS file in our HTML file:

<! DOCTYPE html>

Here are a few points to note:

1.HTML page to introduce our custom uploadpreview.js file

2. Pre-defined an IMG tag to display the preview image, which must have an ID.

3. Find the IMG tag and call the Uploadpreview function

The following results are performed:

Ajax Upload Image File

Ajax upload image file is simple, not so many scenarios, 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 that wraps the uploaded data into this object. Then the Data property is set to False for the Formdata,processdata property when the Ajax upload, indicating that jquery does not process the sent data, and then sets the value of the ContentType property to False. Indicates that the ContentType property of the request header is not set. OK, the main thing is to set these three, after the successful setting, the other processing is consistent with the regular AJAX usage.

Background processing code can be downloaded in the case of the end of the article, I will not show here.

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.