基於.net core2.2的webapi程序,接收客戶端上傳的文件.按照如下寫法,file的值永遠是nullweb
[HttpPost] public void Post([FromForm] IFormFile file) { }
一.有兩種方法解決這個問題:api
1.屬性綁定.在[FromForm]裏添加Name屬性如:[FromForm(name = "file")],客戶端調用時須要保持一致async
// POST api/values
[HttpPost] public void Post([FromForm(Name = "file")] IFormFile file) { }
還能夠和其餘參數一塊兒傳過來測試
// POST api/<controller> [HttpPost] public async Task<IActionResult> UploadFile(string fileName,[FromForm(Name ="file")]IFormFile formFile)
PostMan測試,注意參數名要保持一致,不然收到的值爲nullspa
2.經過Request.Form.Files獲取文件,客戶端能夠任意指定name.net
// POST api/values
[HttpPost] public void Post() { IFormFile formFile= Request.Form.Files[0]; var filePath = @"D:\UploadingFiles\" + formFile.FileName; if (formFile.Length > 0) { using (var stream = new FileStream(filePath, FileMode.Create)) { formFile.CopyTo(stream); } } }
二.客戶端調用代碼rest
var request = new RestRequest(Method.POST); request.AddFile("file", @"d:\1.jpg"); var restClient = new RestClient("http://localhost:63270/api/values"); IRestResponse response = restClient.Execute(request);