在这简短的教程中,我们打算去看如何上传多个文件在 ASP.Net WebAPI 中使用 MultipartFormDataStreamProvider。这一概念基于多部分/格式数据我们可以在这里发布多个文件的内容不仅将 NameValueCollection 作为服务器端提供的常规表单字段。在本教程中我们还看到了如何重写默认行为的MultipartFormDataStreamProvider,将名称存储在一个独特的 BodyPart_ {GUID} 格式中。
适合手机端服务图片接口,支持多个文件(.NET Framework 4.5以上)笔记
[HttpPost] public async Task<HttpResponseMessage> PostSaveImg() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // Prepare CustomMultipartFormDataStreamProvider in which our multipart form // data will be loaded. string fileSaveLocation = HttpContext.Current.Server.MapPath("~/UploadImages"); CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation); List<string> files = new List<string>(); try { // Read all contents of multipart message into CustomMultipartFormDataStreamProvider. await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData file in provider.FileData) { //files.Add(Path.GetFileName(file.LocalFileName)); string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"'); FileInfo fileinfo = new FileInfo(file.LocalFileName); string fileExt = orfilename.Substring(orfilename.LastIndexOf('.')); //定义允许上传的文件扩展名 String fileTypes = "gif,jpg,jpeg,png,bmp"; if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { files.Add("Incorrect image format"); } else { String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo); String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo); fileinfo.CopyTo(Path.Combine(fileSaveLocation, newFileName + fileExt), true); fileinfo.Delete(); files.Add("http://192.168.1.129/UploadImages/" + newFileName + fileExt); } } // Send OK Response along with saved file names to the client. return Request.CreateResponse(HttpStatusCode.OK, files); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { public CustomMultipartFormDataStreamProvider(string path) : base(path) { } public override string GetLocalFileName(HttpContentHeaders headers) { return headers.ContentDisposition.FileName.Replace("\"", string.Empty); } }
原文参考地址:http://blog.csdn.net/greystar/article/details/44562715