MVC4.0 WebAPI上传后的图片默认以字符串bodypart结合Guid来命名,且没有文件后缀,为解决上传图片重命名以及图文结合发布的问题,在实体对象的处理上,可将图片属性定义为byte[]对象,至于图片的重命名,通过重写继承MultipartFormDataStreamProvider类来解决!
参照API的官方文档,上传文件代码大致如下:
public class FileUploadController : ApiController
{
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;//多张图片循环provider.BodyPartFileNames或provider.FileData
//string file1 = provider.GetLocalFileName(provider.FileData[0].Headers);//返回重写的文件名(注意,由于packages包版本的不同,用BodyPartFileNames还是FileData需要留意) // 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; } }
该方法通过直接指定form的action为请求的WebAPI上传地址来处理;如:
<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:8000/api/FileUpload/PostFile">。
另外我们还可以通过向WebAPI提交byte[]形式的文件来解决(以HttpClient方式向WebAPI地址提交上传对象),首先定义文件上传类,以最简单的为例:
相关上传实体类:
上传的Action方法:
WebAPI接收端,主要方法如下(Controller代码略):
Httpclient相关扩展方法如下:
简单调用示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | UploadFileEntity entity = new UploadFileEntity(); entity.FileName = DateTime.Now.ToString( "yyyyMMddHHmmssffff" ) + fileExt; //自定义文件名称,这里以当前时间为例 entity.FileData = GetByte(Request.Files[0].InputStream); var request = JsonConvert.SerializeObject(entity); HttpContent httpContent = new StringContent(request); httpContent.Headers.ContentType = new MediaTypeHeaderValue( "application/json" ); var httpClient = new HttpClient(); public static byte [] GetByte(Stream stream) { byte [] fileData = new byte [stream.Length]; stream.Read(fileData, 0, fileData.Length); stream.Close(); return fileData; } |
联系客服