zoukankan      html  css  js  c++  java
  • [转]微信小程序实现图片上传功能

    本文转自:http://blog.csdn.net/feter1992/article/details/77877659

    前端: 微信开发者工具

    后端:.Net

    服务器:阿里云

    这里介绍微信小程序如何实现上传图片到自己的服务器上

    前端代码

    [javascript] view plain copy print?
    1. data: {  
    2.   productInfo: {}  
    3. },  
    4. //添加Banner  
    5. bindChooiceProduct: function () {  
    6.   var that = this;  
    7.   
    8.   wx.chooseImage({  
    9.     count: 3,  //最多可以选择的图片总数  
    10.     sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有  
    11.     sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有  
    12.     success: function (res) {  
    13.       // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片  
    14.       var tempFilePaths = res.tempFilePaths;  
    15.       //启动上传等待中...  
    16.       wx.showToast({  
    17.         title: '正在上传...',  
    18.         icon: 'loading',  
    19.         mask: true,  
    20.         duration: 10000  
    21.       })  
    22.       var uploadImgCount = 0;  
    23.       for (var i = 0, h = tempFilePaths.length; i < h; i++) {  
    24.         wx.uploadFile({  
    25.           url: util.getClientSetting().domainName + '/home/uploadfilenew',  
    26.           filePath: tempFilePaths[i],  
    27.           name: 'uploadfile_ant',  
    28.           formData: {  
    29.             'imgIndex': i  
    30.           },  
    31.           header: {  
    32.             "Content-Type": "multipart/form-data"  
    33.           },  
    34.           success: function (res) {  
    35.             uploadImgCount++;  
    36.             var data = JSON.parse(res.data);  
    37.             //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }  
    38.             var productInfo = that.data.productInfo;  
    39.             if (productInfo.bannerInfo == null) {  
    40.               productInfo.bannerInfo = [];  
    41.             }  
    42.             productInfo.bannerInfo.push({  
    43.               "catalog": data.Catalog,  
    44.               "fileName": data.FileName,  
    45.               "url": data.Url  
    46.             });  
    47.             that.setData({  
    48.               productInfo: productInfo  
    49.             });  
    50.   
    51.             //如果是最后一张,则隐藏等待中  
    52.             if (uploadImgCount == tempFilePaths.length) {  
    53.               wx.hideToast();  
    54.             }  
    55.           },  
    56.           fail: function (res) {  
    57.             wx.hideToast();  
    58.             wx.showModal({  
    59.               title: '错误提示',  
    60.               content: '上传图片失败',  
    61.               showCancel: false,  
    62.               success: function (res) { }  
    63.             })  
    64.           }  
    65.         });  
    66.       }  
    67.     }  
    68.   });  
    69. }  
    data: {
      productInfo: {}
    },
    //添加Banner
    bindChooiceProduct: function () {
      var that = this;
    
      wx.chooseImage({
        count: 3,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          wx.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          var uploadImgCount = 0;
          for (var i = 0, h = tempFilePaths.length; i < h; i++) {
            wx.uploadFile({
              url: util.getClientSetting().domainName + '/home/uploadfilenew',
              filePath: tempFilePaths[i],
              name: 'uploadfile_ant',
              formData: {
                'imgIndex': i
              },
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: function (res) {
                uploadImgCount++;
                var data = JSON.parse(res.data);
                //服务器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }
                var productInfo = that.data.productInfo;
                if (productInfo.bannerInfo == null) {
                  productInfo.bannerInfo = [];
                }
                productInfo.bannerInfo.push({
                  "catalog": data.Catalog,
                  "fileName": data.FileName,
                  "url": data.Url
                });
                that.setData({
                  productInfo: productInfo
                });
    
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  wx.hideToast();
                }
              },
              fail: function (res) {
                wx.hideToast();
                wx.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) { }
                })
              }
            });
          }
        }
      });
    }

    后端上传代码(将文件上传到服务器临时文件夹内)

    1. [HttpPost]  
    2. public ContentResult UploadFileNew()  
    3. {  
    4.     UploadFileDTO model = new UploadFileDTO();  
    5.     HttpPostedFileBase file = Request.Files["uploadfile_ant"];  
    6.     if (file != null)  
    7.     {  
    8.         //公司编号+上传日期文件主目录  
    9.         model.Catalog = DateTime.Now.ToString("yyyyMMdd");  
    10.         model.ImgIndex = Convert.ToInt32(Request.Form["imgIndex"]);  
    11.   
    12.         //获取文件后缀  
    13.         string extensionName = System.IO.Path.GetExtension(file.FileName);  
    14.   
    15.         //文件名  
    16.         model.FileName = System.Guid.NewGuid().ToString("N") + extensionName;  
    17.   
    18.         //保存文件路径  
    19.         string filePathName = System.IO.Path.Combine(CommonHelper.GetConfigValue("ImageAbsoluteFolderTemp"), model.Catalog);  
    20.         if (!System.IO.Directory.Exists(filePathName))  
    21.         {  
    22.             System.IO.Directory.CreateDirectory(filePathName);  
    23.         }  
    24.         //相对路径  
    25.         string relativeUrl = CommonHelper.GetConfigValue("ImageRelativeFolderTemp");  
    26.         file.SaveAs(System.IO.Path.Combine(filePathName, model.FileName));  
    27.   
    28.         //获取临时文件相对完整路径  
    29.         model.Url = System.IO.Path.Combine(relativeUrl, model.Catalog, model.FileName).Replace("\", "/");  
    30.     }  
    31.     return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));  
    32. }  
    [HttpPost]
    public ContentResult UploadFileNew()
    {
        UploadFileDTO model = new UploadFileDTO();
        HttpPostedFileBase file = Request.Files["uploadfile_ant"];
        if (file != null)
        {
            //公司编号+上传日期文件主目录
            model.Catalog = DateTime.Now.ToString("yyyyMMdd");
            model.ImgIndex = Convert.ToInt32(Request.Form["imgIndex"]);
    
            //获取文件后缀
            string extensionName = System.IO.Path.GetExtension(file.FileName);
    
            //文件名
            model.FileName = System.Guid.NewGuid().ToString("N") + extensionName;
    
            //保存文件路径
            string filePathName = System.IO.Path.Combine(CommonHelper.GetConfigValue("ImageAbsoluteFolderTemp"), model.Catalog);
            if (!System.IO.Directory.Exists(filePathName))
            {
                System.IO.Directory.CreateDirectory(filePathName);
            }
            //相对路径
            string relativeUrl = CommonHelper.GetConfigValue("ImageRelativeFolderTemp");
            file.SaveAs(System.IO.Path.Combine(filePathName, model.FileName));
    
            //获取临时文件相对完整路径
            model.Url = System.IO.Path.Combine(relativeUrl, model.Catalog, model.FileName).Replace("\", "/");
        }
        return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
    }
    1. /// <summary>  
    2. /// 上传文件 返回数据模型  
    3. /// </summary>  
    4. public class UploadFileDTO  
    5. {  
    6.     /// <summary>  
    7.     /// 目录名称  
    8.     /// </summary>  
    9.     public string Catalog { set; get; }  
    10.     /// <summary>  
    11.     /// 文件名称,包括扩展名  
    12.     /// </summary>  
    13.     public string FileName { set; get; }  
    14.     /// <summary>  
    15.     /// 浏览路径  
    16.     /// </summary>  
    17.     public string Url { set; get; }  
    18.     /// <summary>  
    19.     /// 上传的图片编号(提供给前端判断图片是否全部上传完)  
    20.     /// </summary>  
    21.     public int ImgIndex { get; set; }  
    22. }  
    /// <summary>
    /// 上传文件 返回数据模型
    /// </summary>
    public class UploadFileDTO
    {
        /// <summary>
        /// 目录名称
        /// </summary>
        public string Catalog { set; get; }
        /// <summary>
        /// 文件名称,包括扩展名
        /// </summary>
        public string FileName { set; get; }
        /// <summary>
        /// 浏览路径
        /// </summary>
        public string Url { set; get; }
        /// <summary>
        /// 上传的图片编号(提供给前端判断图片是否全部上传完)
        /// </summary>
        public int ImgIndex { get; set; }
    }
    
    1. #region 获取配置文件Key对应Value值  
    2. /// <summary>  
    3. /// 获取配置文件Key对应Value值  
    4. /// </summary>  
    5. /// <param name="key"></param>  
    6. /// <returns></returns>  
    7. public static string GetConfigValue(string key)  
    8. {  
    9.     return ConfigurationManager.AppSettings[key].ToString();  
    10. }  
    11. #endregion  
    #region 获取配置文件Key对应Value值
    /// <summary>
    /// 获取配置文件Key对应Value值
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetConfigValue(string key)
    {
        return ConfigurationManager.AppSettings[key].ToString();
    }
    #endregion

    设置配置文件上传文件对应的文件夹信息

    1. <appSettings>  
    2.   <!--图片临时文件夹 绝对路径-->  
    3.   <add key="ImageAbsoluteFolderTemp" value="D:Images emp" />  
    4.   <!--图片正式文件夹 绝对路径-->  
    5.   <add key="ImageAbsoluteFolderFinal" value="D:Imagesproduct" />  
    6.   
    7.   <!--图片临时文件夹 相对路径-->  
    8.   <add key="ImageRelativeFolderTemp" value="http://192.168.1.79:9009/temp"/>  
    9.   <!--图片正式文件夹 相对路径-->  
    10.   <add key="ImageRelativeFolderFinal" value="http://192.168.1.79:9009/product"/>  
    11. </appSettings>  
    <appSettings>
      <!--图片临时文件夹 绝对路径-->
      <add key="ImageAbsoluteFolderTemp" value="D:Images	emp" />
      <!--图片正式文件夹 绝对路径-->
      <add key="ImageAbsoluteFolderFinal" value="D:Imagesproduct" />
    
      <!--图片临时文件夹 相对路径-->
      <add key="ImageRelativeFolderTemp" value="http://192.168.1.79:9009/temp"/>
      <!--图片正式文件夹 相对路径-->
      <add key="ImageRelativeFolderFinal" value="http://192.168.1.79:9009/product"/>
    </appSettings>

    PS:上传到服务器的临时文件夹内,当用户点击保存才把这些文件移动到正式目录下

    欢迎加入我的微信小程序技术交流群

  • 相关阅读:
    NPOIHelper.cs (NPOI 2.1.1)
    使用哈希加盐法来为密码加密【转】
    让普通控件拥有左键移动窗体的功能
    Reflector反编译.NET文件后修复【转】
    SD卡中FAT32文件格式快速入门(图文详细介绍)【转】
    项目管理知识体系指南(PMBOOK指南)(第5版) 阅读摘要
    数学
    位运算小结
    字符串(1)——Detect Capital
    数组和矩阵(3)——Next Greater Element I
  • 原文地址:https://www.cnblogs.com/freeliver54/p/7728498.html
Copyright © 2011-2022 走看看