/// <summary> /// 圖片上傳保存 /// </summary> /// <returns></returns> [HttpPost] public IHttpActionResult PictureUpload() { try { var picturePath = ""; const string fileTypes = "gif,jpg,jpeg,png,bmp";//運行上傳的圖片文件格式 var content = Request.Content;//獲取或設置 HTTP 消息的內容(當需要獲取HTTP信息是會使用到) const string tempUploadFiles = "/UploadFile/"; //保存路徑 var newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/"; var memoryStreamProvider = new MultipartMemoryStreamProvider();//獲取圖片文件流信息 Task.Run(async () => await Request.Content.ReadAsMultipartAsync(memoryStreamProvider)).Wait(); foreach (var item in memoryStreamProvider.Contents) { if (item.Headers.ContentDisposition.FileName == null) continue; var filename = item.Headers.ContentDisposition.FileName.Replace("\"", ""); var file = new FileInfo(filename); //upload fail(判斷是否是運行上傳的圖片格式) if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1) { return Json(new { code = 0, picturePath = "", msg = "不支持上傳文件類型" }); } //獲取后綴 var extension = Path.GetExtension(filename); var newFileName = Guid.NewGuid().ToString() + extension;//重命名 if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath)) { Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath); } var filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName); picturePath = Path.Combine(tempUploadFiles + newFilePath, newFileName);//圖片相對路徑 var result = item.ReadAsStreamAsync().Result; using (var br = new BinaryReader(result)) { var data = br.ReadBytes((int)result.Length); File.WriteAllBytes(filePath, data);//保存圖片 } } //save successfully return Json(new { code = 1, picturePath = picturePath, msg = "圖片上傳成功~" }); } catch (Exception ex) { return Json(new { code = 0, msg = ex.Message }); } }
前台代碼:
1 <template> 2 <view class="main"> 3 <image :src="imgSrc" mode="aspectFill"></image> 4 <button type="primary" @tap="imguplod()">圖片上傳</button> 5 </view> 6 </template> 7 8 <script> 9 export default { 10 data() { 11 return { 12 imgSrc: "" 13 } 14 }, 15 methods: { 16 imguplod() { 17 let self = this; 18 uni.chooseImage({ 19 sourceType: ['camera', 'album'], 20 sizeType: ['compressed', 'original'], 21 count: 1, 22 success: (res) => { 23 console.log(res) 24 var tempFilePaths = res.tempFilePaths; 25 for (var i = 0; i < tempFilePaths.length; i++) { 26 console.log('圖片地址名稱' + tempFilePaths[i]); 27 wx.uploadFile({ 28 //url: 'http://192.168.1.222:4380/api/upload/photo', 29 url: 'http://localhost:3233/api/ImgUpload/PictureUpload', 30 filePath: tempFilePaths[i], //獲取圖片路徑 31 formData: { 32 'telephone': 'telephone' 33 }, 34 header: { 35 'content-type': 'multipart/form-data' 36 }, 37 name: 'upload', 38 success(res) { 39 console.log(res) 40 var result = JSON.parse(res.data); 41 // self.imgSrc='http://192.168.1.222:4380/'+result.picturePath; 42 43 44 if (result.ok) { 45 self.imgSrc = result.d; 46 } else { 47 uni.showToast({ 48 icon: 'none', 49 title: result.msg 50 }) 51 } 52 } 53 }) 54 } 55 } 56 }) 57 } 58 } 59 } 60 </script> 61 62 <style> 63 </style>