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相關擴展方法如下:
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); }
簡單調用示例如下:
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; }