关于MVC4.0 WebAPI上传图片重命名以及图文结合
MVC4.0 WebAPI上传后的图片默认以字符串bodypart结合Guid来命名,且没有文件后缀,为解决上传图片重命名以及图文结合发布的问题,在实体对象的处理上,可将图片属性定义为byte[]对象,至于图片的重命名,通过重写继承MultipartFormDataStreamProvider类来解决!
参照API的官方文档,上传文件代码大致如下:
public Task<HttpResponseMessage> PostFile() { HttpRequestMessage request = this.Request; string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); //var provider = new MultipartFormDataStreamProvider(root);//原写法 var provider = new RenamingMultipartFormDataStreamProvider(root);//重命名写法 //provider.BodyPartFileNames.sel(kv => kv.Value) var task = request.Content.ReadAsMultipartAsync(provider). ContinueWith<HttpResponseMessage>(o => { string file1 = provider.BodyPartFileNames.First().Value; // this is the file name on the server where the file was saved return new HttpResponseMessage() { Content = new StringContent("File uploaded." + file1) }; } ); return task; }
再来看看继承MultipartFormDataStreamProvider的类:
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider { public string Root { get; set; } //public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; } public RenamingMultipartFormDataStreamProvider(string root) : base(root) { Root = root; } public override string GetLocalFileName(HttpContentHeaders headers) { string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes. if (filePath.StartsWith(@"""") && filePath.EndsWith(@"""")) filePath = filePath.Substring(1, filePath.Length - 2); var filename = Path.GetFileName(filePath); var extension = Path.GetExtension(filePath); var contentType = headers.ContentType.MediaType; return filename; } } 待续...