Webapi文件上傳
阿新 • • 發佈:2018-06-08
lin 引號 EDA lena space request fix tdi form
1/ multipart/form-data方式
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace FileUpload.Controllers { [RoutePrefix("api/upload")] public class UploadController : ApiController { [Route("file"), HttpPost] public async Task<bool> ImgFromDataUploadAsync() { if (!Request.Content.IsMimeMultipartContent()) throw new Exception("is no file"); //web api 獲取項目根目錄下指定的文件下 var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images"); //如果路徑不存在,創建路徑 if (!Directory.Exists(root)) Directory.CreateDirectory(root); var provider = new MultipartFormDataStreamProvider(root); //文件已經上傳 但是文件沒有後綴名 需要給文件添加後綴名 await Request.Content.ReadAsMultipartAsync(provider);foreach (var file in provider.FileData) { //這裏獲取含有雙引號‘" ‘ string filename = file.Headers.ContentDisposition.FileName.Trim(‘"‘); //獲取對應文件後綴名 string fileExt = filename.Substring(filename.LastIndexOf(‘.‘)); FileInfo fileinfo = new FileInfo(file.LocalFileName); //fileinfo.Name 上傳後的文件路徑 此處不含後綴名 //修改文件名 添加後綴名 string newFilename = fileinfo.Name + fileExt; //最後保存文件路徑 string saveUrl = Path.Combine(root, newFilename); fileinfo.MoveTo(saveUrl); } return true; } } }
Webapi文件上傳