关于MVC4.0 WebAPI上传图片重命名以及图文结合
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地址提交上传对象),首先定义文件上传类,以最简单的为例:
相关上传实体类:

/// <summary> /// 文件上传 /// </summary> public class UploadFileEntity { /// <summary> /// 文件名 /// </summary> public string FileName { get; set; } /// <summary> /// 文件二进制数据 /// </summary> public byte[] FileData { get; set; } } /// <summary> /// 文件上传结果信息 /// </summary> public class ResultModel { /// <summary> /// 返回结果 0: 失败,1: 成功。 /// </summary> public int Result { get; set; } /// <summary> /// 操作信息,成功将返回空。 /// </summary> public string Message { get; set; } }
上传的Action方法:

public ActionResult UploadImage() { byte[] bytes = null; using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { bytes = binaryReader.ReadBytes(Request.Files[0].ContentLength); } string fileExt = Path.GetExtension(Request.Files[0].FileName).ToLower(); UploadFileEntity entity = new UploadFileEntity(); entity.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;//自定义文件名称,这里以当前时间为例 entity.FileData = bytes; ResultModel rm = HttpClientOperate.Post<ResultModel>("/UploadFile/SaveFile", APIUrl, entity);//封装的POST提交方法,APIUrl为提交地址,大家可还原为HttpClient的PostAsync方式提交 return Content("{\"msg\":\"" + rm.Message + "\"}"); }
WebAPI接收端,主要方法如下(Controller代码略):

public string SaveFile(UploadFileEntity entity) { string retVal = string.Empty; if (entity.FileData != null && entity.FileData.Length > 0) {//由于此例生成的文件含子目录文件等多层,下面处理方法不一定适合大家,保存地址处理大家根据自己需求来 entity.FileName = entity.FileName.ToLower().Replace("\\", "/"); string savaImageName = HttpContext.Current.Server.MapPath(ConfigOperate.GetConfigValue("SaveBasePath")) + entity.FileName;//定义保存地址 string path = savaImageName.Substring(0, savaImageName.LastIndexOf("/")); DirectoryInfo Drr = new DirectoryInfo(path); if (!Drr.Exists) { Drr.Create(); } FileStream fs = new FileStream(savaImageName, FileMode.Create, FileAccess.Write); fs.Write(entity.FileData, 0, entity.FileData.Length); fs.Flush(); fs.Close(); #region 更新数据等其他逻辑 #endregion retVal = ConfigOperate.GetConfigValue("ImageUrl") + entity.FileName; } return retVal;//返回文件地址 }
Httpclient相关扩展方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public static T Post<T>( string requestUri, string webapiBaseUrl, HttpContent httpContent) { var httpClient = new HttpClient() { MaxResponseContentBufferSize = 1024 * 1024 * 2, BaseAddress = new Uri(webapiBaseUrl) }; T t = Activator.CreateInstance<T>(); HttpResponseMessage response = new HttpResponseMessage(); try { httpClient.PostAsync(requestUri, httpContent).ContinueWith((task) => { if (task.Status != TaskStatus.Canceled) { response = task.Result; } }).Wait(waitTime); if (response.Content != null && response.StatusCode == HttpStatusCode.OK) { t = response.Content.ReadAsAsync<T>().Result; } return t; } catch { return t; } finally { httpClient.Dispose(); response.Dispose(); } } public static T Post<T>( string requestUri, string webapiBaseUrl, string jsonString) { HttpContent httpContent = new StringContent(jsonString); httpContent.Headers.ContentType = new MediaTypeHeaderValue( "application/json" ); return Post<T>(requestUri, webapiBaseUrl, httpContent); } public static T Post<T>( string requestUri, string webapiBaseUrl, object obj = null ) { string jsonString = JsonOperate.Convert2Json< object >(obj); //可换成Newtonsoft.Json的JsonConvert.SerializeObject方法将对象转化为json字符串 return Post<T>(requestUri, webapiBaseUrl, jsonString); } |
简单调用示例如下:
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(); httpClient.PostAsync( "http://localhost:7901/api/FileUpload/SaveFile" , httpContent); public static byte [] GetByte(Stream stream) { byte [] fileData = new byte [stream.Length]; stream.Read(fileData, 0, fileData.Length); stream.Close(); return fileData; } |
作者:白云任去留
如果你觉得这篇文章对你有所帮助或启发,请点击右侧【推荐】,谢谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架