ASP.NET WEB API 使用MultipartFormDataStreamProvider上傳文件

摸索過程中

參照:https://blog.shibayan.jp/entry/20150319/1426750361

public async Task<IHttpActionResult> FileUpload()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return StatusCode(HttpStatusCode.UnsupportedMediaType);
    }
    var rootPath = Path.GetTempPath();
    var provider = new MultipartFormDataStreamProvider(rootPath);

    await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var file in provider.FileData)
    {
        var fileInfo = new FileInfo(file.LocalFileName);
    }
    return Ok();
}

但存儲文件時名稱以BodyPart_打頭,不是上傳的真實文件名,需要重構原始的MultipartFormDataStreamProvider方法,如下

public class MultipartFileWithExtensionStreamProvider : MultipartFileStreamProvider
    {
        public MultipartFileWithExtensionStreamProvider(string rootPath)
            : base(rootPath) { }
        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }

問題解決了

完整代碼如下

        [HttpPost]
        [Route("api/file/upload")]
        public async Task<HttpResponseMessage> FileUpload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            
            Dictionary<string, string> queryString = AspUtil.GetRequestUriQueryDictionary(Request);
            queryString.TryGetValue("rootPath", out string rootPath);
            rootPath = rootPath?? @"C:\RelaySvrUpdater";
            var provider = new MultipartFileWithExtensionStreamProvider(rootPath);
            List<string> files = new List<string>();

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    files.Add(Path.GetFileName(file.LocalFileName));
                }
                return Request.CreateResponse(HttpStatusCode.OK, files);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

    public class MultipartFileWithExtensionStreamProvider : MultipartFileStreamProvider
    {
        public MultipartFileWithExtensionStreamProvider(string rootPath)
            : base(rootPath) { }
        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }

Postman調試,rootPath可不填

header中 Content-Type :multipart/form-data ,body中選擇form-data,然後選擇上傳File

不支持text格式上傳,會報錯;

優化:返回結果可以拼裝成json格式,這樣更清晰些

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章