Home > Web Front-end > H5 Tutorial > body text

H5 mobile phone image upload plug-in code

不言
Release: 2018-06-11 16:20:21
Original
5719 people have browsed it

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(&#39;<input id="fileImage" style="opacity:0;position:absolute;top: 0;left: 0;width:100%;height:100%" type="file" size="30" name="fileselect[]" &#39; + multiple + &#39;>&#39;);

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() + &#39;%&#39;);
   });
   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);
Copy after login

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");
 }
Copy after login

 [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);

 }
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!