微信小程序图片上传后台接口

/// <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>

 

posted @ 2020-07-09 17:07  逍遥Phoenix  阅读(1799)  评论(0编辑  收藏  举报