H5 mobile phone image upload plug-in code
This article mainly introduces the H5 image upload plug-in in detail. Based on zepto, it supports multi-file upload, progress and image preview. It has certain reference value. Interested friends can refer to it
Based on zepto, supports multi-file upload, progress and picture preview, for mobile phones.
(function ($) { $.extend($, { fileUpload: function (options) { var para = { multiple: true, filebutton: ".filePicker", uploadButton: null, url: "/home/MUploadImg", filebase: "mfile",//mvc后台需要对应的名称 auto: true, previewZoom: null, uploadComplete: function (res) { console.log("uploadComplete", res); }, uploadError: function (err) { console.log("uploadError", err); }, onProgress: function (percent) { // 提供给外部获取单个文件的上传进度,供外部实现上传进度效果 console.log(percent); }, }; para = $.extend(para, options); var $self = $(para.filebutton); //先加入一个file元素 var multiple = ""; // 设置多选的参数 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 core = { fileSelected: function () { var files = (doms.fileToUpload)[0].files; var count = files.length; console.log("共有" + count + "个文件"); 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("开始上传"); var formdata = new FormData(); formdata.append(para.filebase, file);//这个名字要和mvc后台配合 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", para.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); // 使用FileReader方法显示图片内容 var reader = new FileReader(); reader.onload = (function (aImg) { return function (e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); } } doms.fileToUpload.on("change", function () { //doms.progress.find("span").width("0"); console.log("选中了文件"); core.fileSelected(); }); console.log("初始化!"); //绑定事件 $(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: Uploading still relies on the file element, so I added a hidden one at the beginning. Simple hiding will cause some problems, and sometimes it cannot be triggered. file change event. So we used transparency and set the parent class to relative position. Then obtain the file to be uploaded through the file's change event and put it into formdata, and then use xmlHttpRequest to make the request. The progress bar is directly bound to the process event. The file preview is filereader. Another thing to note is the filebase parameter, which corresponds to the name of the parameter of the MVC background upload method. If it is inconsistent, the background will not be able to obtain the file. I won’t talk about the callback function.
[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 = "文件格式不对!" }, 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);// 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 //string saveName = Guid.NewGuid() + fileExtension; // 保存文件名称 这是个好方法。 string saveName = Encrypt.GenerateOrderNumber() + fileExtension; // 保存文件名称 这是个好方法。 file.SaveAs(uploadpath + saveName); return Json(new { Success = true, SaveName = path + saveName }); } return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet); }
Call:
<p class="page" id="upload"> <h2>UploadImg</h2> <p id="dd" class="filePicker">点击选择文件</p> <p id="preview"></p> </p> <script> $.fileUpload({ filebutton: "#dd", previewZoom: "#preview" }); </script>
Expands to $object instead of $.fn because the latter is inconvenient when binding events in zepto. Passing id or style name is easy to bind. The mobile phone can automatically bring up the camera and photo album. By default, images are not previewed. The preview area needs to be specified. The progress bar needs to be styled by itself. Only the progress value is returned.
The effect of transmitting 2 pictures at the same time:
The above is the entire content of this article, I hope it will be useful for everyone’s learning For help, please pay attention to the PHP Chinese website for more related content!
Related recommendations:
H5 implements the function code to upload local images and preview them
##
The above is the detailed content of H5 mobile phone image upload plug-in code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

The advantages of H5 page production include: lightweight experience, fast loading speed, and improving user retention. Cross-platform compatibility, no need to adapt to different platforms, improving development efficiency. Flexibility and dynamic updates, no audit required, making it easier to modify and update content. Cost-effective, lower development costs than native apps.

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.
