Multi-file upload and preview plug-ins on H5 mobile phones,

Source: Internet
Author: User

Multi-file upload and preview plug-ins on H5 mobile phones,

Based on zepto, it supports Multifile upload, progress, and image preview for mobile phones.

(Function ($) {$. extend ($, {fileUpload: function (options) {var para = {multiple: true, filebutton :". filePicker ", uploadButton: null, url:"/home/MUploadImg ", filebase:" mfile ", // The name auto: true, previewZoom: null, uploadComplete: function (res) {console. log ("uploadComplete", res) ;}, uploadError: function (err) {console. log ("uploadError", err) ;}, onProgress: function (percent ){// Provides external access to obtain the upload progress of a single file, allowing external access to achieve the upload progress. log (percent) ;},}; para = $. extend (para, options); var $ self = $ (para. filebutton); // first add a file element var multiple = ""; // set the multiple-choice parameter para. multiple? Multiple = "multiple": multiple = ""; $self.css ('position', 'relative '); $ self. append ('<input id = "fileImage" style = "opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100% "type =" file "size =" 30 "name =" fileselect [] "'+ multiple +'> '); var doms = {" fileToUpload ": $ self. parent (). find ("# fileImage"), // "thumb": $ self. find (". thumb "), //" progress ": $ self. find (". upload-progress ")}; var cor E = {fileSelected: function () {var files = (doms. fileToUpload) [0]. files; var count = files. length; console. log ("Total" + count + "files"); for (var I = 0; I <count; I ++) {var item = files [I]; console. log (item. size); if (para. auto) {core. uploadFile (item);} core. previewImage (item) ;}}, uploadFile: function (file) {console. log ("START upload"); var formdata = new FormData (); formdata. append (para. filebase, File); // This name should be used with the mvc background var xhr = new XMLHttpRequest (); xhr. upload. addEventListener ("progress", function (e) {var percentComplete = Math. round (e. loaded * 100/e. total); para. onProgress (percentComplete. toString () + '%') ;}); xhr. addEventListener ("load", function (e) {para. uploadComplete (xhr. responseText) ;}); xhr. addEventListener ("error", function (e) {para. uploadError (e) ;}); xhr. open ("post", p Ara. url, true); // xhr. setRequestHeader ("X_FILENAME", file. name); xhr. send (formdata) ;}, uploadFiles: function () {var files = (doms. fileToUpload) [0]. files; for (var I = 0; I <files. length; I ++) {core. uploadFile (files [I]) ;}}, previewImage: function (file) {if (! Para. previewZoom) return; var img = document. createElement ("img"); img. file = file; $ (para. previewZoom ). append (img); // use the FileReader method to display the image content var reader = new FileReader (); reader. onload = (function (aImg) {return function (e) {aImg. src = e.tar get. result ;};}) (img); reader. readAsDataURL (file) ;}} doms. fileToUpload. on ("change", function () {// doms. progress. find ("span "). width ("0"); console. log ("select File "); core. fileSelected () ;}); console. log (" initialization! "); // Bind event $ (document ). on ("click", para. filebutton, function () {console. log ("clicked"); // doms. fileToUpload. click () ;}); if (para. uploadButton) {$ (document ). on ("click", para. uploadButton, function () {core. uploadFiles () ;}}}) ;}( Zepto );

Simple explanation: the upload still depends on the file element. Therefore, a hidden element is added at the beginning, which may cause some problems. Sometimes the file change event cannot be triggered. Therefore, transparency is used to set the parent class to a relative position. Then, get the file to be uploaded through the change event of file and put it into formdata, and then send a request using xmlHttpRequest. The progress bar is a process event that is directly bound. File preview is filereader. In addition, you must note that the filebase parameter corresponds to the parameter name of the MVC background upload method. If they are inconsistent, the background will not be able to get the file. The callback function will not be mentioned.

 [HttpPost] public ActionResult MUploadImg(HttpPostedFileBase mfile) {  return UploadImg(mfile, "Mobile"); }
[HttpPost] public ActionResult UploadImg (HttpPostedFileBase file, string dir = "UserImg") {if (CheckImg (file, imgtypes )! = "OK") return Json (new {Success = false, Message = "incorrect file format! "}, JsonRequestBehavior. AllowGet); if (file! = Null) {var path = "~ /Content/UploadFiles/"+ dir +"/"; var uploadpath = Server. MapPath (path); if (! Directory. exists (uploadpath) {Directory. createDirectory (uploadpath);} string fileName = Path. getFileName (file. fileName); // the name of the original file string fileExtension = Path. getExtension (fileName); // file extension // string saveName = Guid. newGuid () + fileExtension; // This is a good way to save the file name. String saveName = Encrypt. GenerateOrderNumber () + fileExtension; // This is a good way to save the file name. File. saveAs (uploadpath + saveName); return Json (new {Success = true, SaveName = path + saveName});} return Json (new {Success = false, message = "select the file to upload! "}, JsonRequestBehavior. AllowGet );}

Call:

<Div class = "page" id = "upload"> 

Extended to $ object without extended to $. fn, because the latter is inconvenient when binding events in zepto, and it is easy to bind the id or style name. The mobile phone can automatically call up the camera and album. By default, no picture is previewed. You need to create a preview area. You must write a style on the progress bar and only return the progress value.

Upload two results at the same time:

Refer to two blogs:

Javascript html5 mobile terminals can easily upload files

Html5 File Upload preview function

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.