微信小程序開發之多圖片上傳+服務端接收

前言:

  業務需求,此次須要作一個微信小程序同時選中三張圖片一塊兒上傳到服務端的功能,後端使用的.Net WebApi接收數據保存。html

使用技術:

  在這章中將會使用到微信小程序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
屬性 類型 默認值 必填 說明
count number 9 最多能夠選擇的圖片張數
sizeType Array.<string> ['original', 'compressed'] 所選的圖片的尺寸
sourceType Array.<string> ['album', 'camera'] 選擇圖片的來源
success function   接口調用成功的回調函數
fail function   接口調用失敗的回調函數
complete function   接口調用結束的回調函數(調用成功、失敗都會執行)

wx.uploadFile()概述:

  將本地資源上傳到服務器。客戶端發起一個 HTTPS POST 請求,其中 content-type 爲 multipart/form-data,詳細瞭解請閱讀微信小程序開發文檔(https://developers.weixin.qq.com/miniprogram/dev/api/wx.uploadFile.html?q=wx.uploadFile)。微信小程序

參數

Object object
屬性 類型 默認值 必填 說明
url string   開發者服務器地址
filePath string   要上傳文件資源的路徑
name string   文件對應的 key,開發者在服務端能夠經過這個 key 獲取文件的二進制內容
header Object   HTTP 請求 Header,Header 中不能設置 Referer
formData Object   HTTP 請求中其餘額外的 form data
success function   接口調用成功的回調函數
fail function   接口調用失敗的回調函數
complete function   接口調用結束的回調函數(調用成功、失敗都會執行)

廢話很少說,上代碼:

.Wxml code:

<view class='form-s2'>
<view>門店照片(請選擇三張)</view>
<view>
<view class="weui-uploader__files" id="uploaderFiles">
<block wx:for="{{files}}" wx:key="*this">
<view class="weui-uploader__file" bindtap="previewImage" id="{{item}}" style='margin-top:11px;'>
<image class="weui-uploader__img" src="{{item}}" mode="aspectFill" />
</view>
</block>
</view>
<view class="weui-uploader__input-box" style='top:11px;'>
<view class="weui-uploader__input" bindtap="chooseImage"></view>
</view>
</view>
</view>

.Js code:

Page({
  /**
   * 頁面的初始數據
   */
data:
{
  files: [], //門店圖片信息,數組圖片保存做爲數據源
},
,
  /**
   * 多圖片上傳
   */
chooseImage: function(e) {
var that = this;
if (that.data.files.length > 2) {
 resource.notishi("抱歉最多隻容許上傳三張圖片喲~");
 return false;
}

wx.chooseImage({
count: 3, //默認9張,這裏設置三張
sizeType: ['original', 'compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
sourceType: ['album', 'camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
success: function(res) {
wx.showLoading({
title: '上傳中,請稍等...',
})
// 返回選定照片的本地文件路徑列表,tempFilePath能夠做爲img標籤的src屬性顯示圖片
var tempFilePaths = res.tempFilePaths;
 //多圖片上傳,tempFilePaths本地圖片地址爲一個數組,遍歷調用服務器圖片上傳接口便可實現多圖保存
for (var i = 0; i < tempFilePaths.length; i++) {
console.log('圖片地址名稱' + tempFilePaths[i]);
wx.uploadFile({
 url: app.globalData.hostUrl + "/api/PictureUpload/Upload", //此處爲實際接口地址
filePath: tempFilePaths[i], //獲取圖片路徑
header: {
'content-type': 'multipart/form-data'
},
 name: 'upload',
success: function(res) {
wx.hideLoading();
let Result = JSON.parse(res.data);
console.log(Result);//接收返回來的服務器圖片地址
if (Result.code == 1) {
let picurl = app.globalData.hostUrl + Result.picurl;
console.log(picurl);
 that.setData({
files: that.data.files.concat(picurl)
});
} else {
 resource.notishi("網絡異常,請稍後再試");
}
},
fail: function(res) {
wx.hideLoading()
wx.showToast({
title: '上傳失敗,請從新上傳',
icon: 'none',
duration: 2000
})
},
})
}
}
})
},
 //圖片預覽
previewImage: function(e) {
wx.previewImage({
current: e.currentTarget.id, // 當前顯示圖片的http連接
urls: this.data.files // 須要預覽的圖片http連接列表
})},
})

後端圖片接收保存 code(.Net WebApi)

/// <summary>
/// 圖片上傳保存
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult Upload()
{
 try
{
var content = Request.Content;//獲取http設置的消息和內容
var tempUploadFiles = "/Images/Wechatimages/";//保存路徑
var newFileName = "";
string filePath = "";
string extname = "";
string returnurl = "";
var sp = new MultipartMemoryStreamProvider();
Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();

foreach (var item in sp.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
FileInfo file = new FileInfo(filename);
string fileTypes = "gif,jpg,jpeg,png,bmp";
if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
{
throw new ApplicationException("不支持上傳文件類型");
}

//獲取後綴
extname = System.IO.Path.GetExtension(filename);//獲取文件的拓展名稱
newFileName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
string newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/";
if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath))
{
Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath);
}
filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName);
 returnurl = Path.Combine(tempUploadFiles + newFilePath, newFileName);//圖片相對路徑
var ms = item.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
var data = br.ReadBytes((int)ms.Length);
File.WriteAllBytes(filePath, data);//保存圖片
}
}
}
return Json(new {code=1,picurl= returnurl,msg="success" }) ;
}
catch (Exception ex)
{
return Json(new { code =0,msg=ex.Message});
}
}

效果圖展現(美女喲,嘻嘻):

總結:

  其實作完回過頭來想一想,不管是微信小程序圖片上傳仍是html頁面圖片上傳原理其實都是差很少,都是經過content-type 爲 multipart/form-data 標識,經過http post將圖片資源文件以二進制的編碼格式傳日後臺,而後後臺獲取對應文件流進行數據圖片保存。總結的不夠到位,有什麼沒作好的望各位大佬指點。api

相關文章
相關標籤/搜索