赞
踩
选择菜单 “文件-》新建醒目-》web -》ASP.NET Web 应用程序”
输入项目名称和位置,确定,进入模板选择页面。
选择 WEB API 模板(选择Web API 时会添加对MVC 的支持)新建API控制器
Controllers ------》右键 ------》添加---------》控制器---------》webapi 2控制器 - 空
/// <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 }); } }
wx.uploadFile({
url: 'http://yangyoushan.top:83/api/Default/PictureUpload', //接口地址
filePath: item.local,//本地地址
name: 'file',
formData: {
'user': 'test'
},
success(res) {
var data= JSON.parse(res.data)
const url = 'http://yangyoushan.top:83' + data.picturePath
list[idx].url = url
}
})
参考文献wx.uploadFile
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。