[WebAPI2] 使用WebAPI上傳多圖片(multipart/form-data)

參考網址:https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

public async Task<HttpResponseMessage> PostFormData()
    {
// Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            //取得目錄指定的地方
            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.塞入檔案,上傳文件,但是沒有後綴,需要後續改名
                await Request.Content.ReadAsMultipartAsync(provider);

                int i = 0;
                // This illustrates how to get the file names.
                foreach (MultipartFileData file in provider.FileData)
                {
                    //取得含有雙引號的
                    string filename = file.Headers.ContentDisposition.FileName.Trim('"');
                    //取得後綴
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));

                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(file.LocalFileName);
                    //fileinfo.Name 上傳後的文件路徑不含後綴
                    //修改文件名添加後綴名

                    string newFileName = "test"+i + fileExt;
                    i++;
                    //最後保存文件路徑
                    string saveUrl = System.IO.Path.Combine(root, newFileName);
                    fileInfo.MoveTo(saveUrl);


                    //System.Diagnostics.Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //System.Diagnostics.Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
}