温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在微信小程序中实现图片上传功能

发布时间:2021-05-22 17:12:24 来源:亿速云 阅读:327 作者:Leah 栏目:web开发

如何在微信小程序中实现图片上传功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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://cache.yisu.com/upload/information/20200622/114/41870.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) { } 
      }) 
     } 
    }); 
   } 
  } 
 }); 
}

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

[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)); 
}
/// <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; } 
}
#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

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

<appSettings> 
 <!--图片临时文件夹 绝对路径--> 
 <add key="ImageAbsoluteFolderTemp" value="D:\Images\temp" /> 
 <!--图片正式文件夹 绝对路径--> 
 <add key="ImageAbsoluteFolderFinal" value="D:\Images\product" /> 
 
 <!--图片临时文件夹 相对路径--> 
 <add key="ImageRelativeFolderTemp" value="http://192.168.1.79:9009/temp"/> 
 <!--图片正式文件夹 相对路径--> 
 <add key="ImageRelativeFolderFinal" value="http://192.168.1.79:9009/product"/> 
</appSettings>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI