微信小程序开发中如何做好多图片上传+服务端接收?

在开发微信小程序的过程中经常会遇到这样的需求,需要做一个小程序同时选中三张图片一起上传到服务端,后端使用的.NET WEBAPI接收数据保存。如何进行操作?春哥团队技术大东分享如下:

使用技术:将会使用到微信小程序wx.uploadFile(Object object) 和wx.chooseImage(Object object)接口,对图片大小和来源进行上传。

wx.chooseImage() 概述: 
  从本地相册选择图片或使用相机拍照,详细了解请阅读微信小程序开发文档(https://developers.weixin.qq.com/miniprogram/dev/api/wx.chooseImage.html?search-key=wx.chooseimage

参数 
Object object

wx.uploadFile()概述:

  将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data,详细了解请阅读微信小程序开发文档(https://developers.weixin.qq.com/miniprogram/dev/api/wx.uploadFile.html?q=wx.uploadFile)。

参数

废话不多说,上代码:

.Wxml code:


 
  1. class='form-s2'>
  2. 门店照片(请选择三张)
  3.  
  4. class="weui-uploader__files" id="uploaderFiles">
  5. wx:for="{{files}}" wx:key="*this">
  6. class="weui-uploader__file" bindtap="previewImage" id="{{item}}" style='margin-top:11px;'>
  7. class="weui-uploader__img" src="{{item}}" mode="aspectFill" />
  8.  
  9.  
  10.  
  11. class="weui-uploader__input-box" style='top:11px;'>
  12. class="weui-uploader__input" bindtap="chooseImage">
  13.  
  14.  
  15.  

.Js code:


 
  1. Page({
  2. /**
  3. * 页面的初始数据
  4. */
  5. data:
  6. {
  7. files: [], //门店图片信息,数组图片保存作为数据源
  8. },
  9. ,
  10. /**
  11. * 多图片上传
  12. */
  13. chooseImage: function(e) {
  14. var that = this;
  15. if (that.data.files.length > 2) {
  16. resource.notishi("抱歉最多只允许上传三张图片哟~");
  17. return false;
  18. }
  19.  
  20. wx.chooseImage({
  21. count: 3, //默认9张,这里设置三张
  22. sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  23. sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  24. success: function(res) {
  25. wx.showLoading({
  26. title: '上传中,请稍等...',
  27. })
  28. // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
  29. var tempFilePaths = res.tempFilePaths;
  30. //多图片上传,tempFilePaths本地图片地址为一个数组,遍历调用服务器图片上传接口即可实现多图保存
  31. for (var i = 0; i < tempFilePaths.length; i++) {
  32. console.log('图片地址名称' + tempFilePaths[i]);
  33. wx.uploadFile({
  34. url: app.globalData.hostUrl + "/api/PictureUpload/Upload", //此处为实际接口地址
  35. filePath: tempFilePaths[i], //获取图片路径
  36. header: {
  37. 'content-type': 'multipart/form-data'
  38. },
  39. name: 'upload',
  40. success: function(res) {
  41. wx.hideLoading();
  42. let Result = JSON.parse(res.data);
  43. console.log(Result);//接收返回来的服务器图片地址
  44. if (Result.code == 1) {
  45. let picurl = app.globalData.hostUrl + Result.picurl;
  46. console.log(picurl);
  47. that.setData({
  48. files: that.data.files.concat(picurl)
  49. });
  50. } else {
  51. resource.notishi("网络异常,请稍后再试");
  52. }
  53. },
  54. fail: function(res) {
  55. wx.hideLoading()
  56. wx.showToast({
  57. title: '上传失败,请重新上传',
  58. icon: 'none',
  59. duration: 2000
  60. })
  61. },
  62. })
  63. }
  64. }
  65. })
  66. },
  67. //图片预览
  68. previewImage: function(e) {
  69. wx.previewImage({
  70. current: e.currentTarget.id, // 当前显示图片的http链接
  71. urls: this.data.files // 需要预览的图片http链接列表
  72. })},
  73. })

后端图片接收保存 code(.Net WEBAPI)

 
  1. ///
  2. /// 图片上传保存
  3. ///
  4. ///
  5. [HttpPost]
  6. public IHttpActionResult Upload()
  7. {
  8. try
  9. {
  10. var content = Request.Content;//获取http设置的消息和内容
  11. var tempUploadFiles = "/Images/Wechatimages/";//保存路径
  12. var newFileName = "";
  13. string filePath = "";
  14. string extname = "";
  15. string returnurl = "";
  16. var sp = new MultipartMemoryStreamProvider();
  17. Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();
  18.  
  19. foreach (var item in sp.Contents)
  20. {
  21. if (item.Headers.ContentDisposition.FileName != null)
  22. {
  23. var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
  24. FileInfo file = new FileInfo(filename);
  25. string fileTypes = "gif,jpg,jpeg,png,bmp";
  26. if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
  27. {
  28. throw new ApplicationException("不支持上传文件类型");
  29. }
  30.  
  31. //获取后缀
  32. extname = System.IO.Path.GetExtension(filename);//获取文件的拓展名称
  33. newFileName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
  34. string newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/";
  35. if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath))
  36. {
  37. Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath);
  38. }
  39. filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName);
  40. returnurl = Path.Combine(tempUploadFiles + newFilePath, newFileName);//图片相对路径
  41. var ms = item.ReadAsStreamAsync().Result;
  42. using (var br = new BinaryReader(ms))
  43. {
  44. var data = br.ReadBytes((int)ms.Length);
  45. File.WriteAllBytes(filePath, data);//保存图片
  46. }
  47. }
  48. }
  49. return Json(new {code=1,picurl= returnurl,msg="success" }) ;
  50. }
  51. catch (Exception ex)
  52. {
  53. return Json(new { code =0,msg=ex.Message});
  54. }
  55. }

 



总结:

  其实做完回过头来想想,无论是微信小程序图片上传还是html页面图片上传原理其实都是差不多,都是通过content-type 为 multipart/form-data 标识,通过http post将图片资源文件以二进制的编码格式传往后台,然后后台获取对应文件流进行数据图片保存。总结的不够到位,有什么没做好的望各位大佬指点。
 



来源:春哥技术博客,欢迎分享,转载请注明出处。(欢迎加春哥团队客服微信号:taike668)

本文地址:https://www.cgtblog.com/wx/3476.html
上一篇:小程序为什么要配置https域名——最全      下一篇:从App竟然可以直接打开小程序?