1. 程式人生 > >微信小程式實現圖片上傳功能

微信小程式實現圖片上傳功能

前端: 微信開發者工具

後端:.Net

伺服器:阿里雲

這裡介紹微信小程式如何實現上傳圖片到自己的伺服器上

前端程式碼

data: {
  productInfo: {}
},
//上傳圖片
uploadImage: function () {
  var that = this;

  wx.chooseImage({
    count: 1,  //最多可以選擇的圖片總數
    sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
    sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
    success: function (res) {
      // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
      var tempFilePaths = res.tempFilePaths;
      //啟動上傳等待中...
      wx.showToast({
        title: '正在上傳...',
        icon: 'loading',
        mask: true,
        duration: 10000
      })

        wx.uploadFile({
          url: '192.168.1.1/home/uploadfilenew',
          filePath: tempFilePaths[0],
          name: 'uploadfile_ant',
          formData: {
          },
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: function (res) {
            var data = JSON.parse(res.data);
            //伺服器返回格式: { "Catalog": "testFolder", "FileName": "1.jpg", "Url": "https://test.com/1.jpg" }
            console.log(data);
          },
          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");

        //獲取檔案字尾
        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>

PS:上傳到伺服器的臨時資料夾內,當用戶點選儲存才把這些檔案移動到正式目錄下

小程式演示

自定義上傳頭像

不清楚的可以加微信聯絡我