现在微信或者app这么流行,就会用到微信端或者APP端调用webapi提供的图片上传接口实现上传的功能了,主要代码实现如下:
protected string FileUpload(string dirPath) { if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string dirTempPath = HttpContext.Current.Server.MapPath(dirPath); if (!Directory.Exists(dirTempPath)) { Directory.CreateDirectory(dirTempPath); } //设置上传目录 var provider = new MultipartFormDataStreamProvider(dirTempPath); Task.Run(async () => await Request.Content.ReadAsMultipartAsync(provider)).Wait(); var file = provider.FileData[0]; //最大文件大小 const int maxSize = 10000000; //定义允许上传的文件扩展名 const string fileTypes = "gif,jpg,jpeg,png,bmp,xls"; string oldFileName = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); string FilePath = ""; var fileInfo = new FileInfo(file.LocalFileName); if (fileInfo.Length <= 0) { throw new BaseException("请选择上传文件。"); } if (fileInfo.Length > maxSize) { throw new BaseException("上传文件大小超过限制。"); } var fileExt = oldFileName.Substring(oldFileName.LastIndexOf('.')); if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { throw new BaseException("不支持上传文件类型,只支持"+ fileTypes); } string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo); string filePath = Path.Combine(dirPath, newFileName + fileExt).Replace("~", "").Replace("\\", "/"); FilePath = Path.Combine(dirTempPath, newFileName + fileExt); fileInfo.CopyTo(FilePath, true); fileInfo.Delete(); return filePath; }
写个DEMO自己测试下:
<html> <body> <form action="/api/Upload/UploadImg" method="post" enctype="multipart/form-data"> <input type="file" name="filename"/> <input type="input" name="Folder" value="1" /> <input type="submit" value="上传" /> </form> </body> </html
当然control层是这样的:
[HttpPost] public string UploadImg() { int Folder = HttpContext.Current.Request.Form["Folder"]; return FileUpload(Folder); }