Send image with HttpClient to POST WebApi and consume the data

前端 未结 2 1913
春和景丽
春和景丽 2021-01-27 14:58

My HttpClient sends the image with PostAsync. I am not really sure what to do now since this is my first REST Api and I can\'t really adapt the things

2条回答
  •  北海茫月
    2021-01-27 15:18

    1.Your controller should look like this:

    //For .net core 2.1
    [HttpPost]
    public IActionResult Index(List files)
    {
        //Do something with the files here. 
        return Ok();
    }
    
    //For previous versions
    
    [HttpPost]
    public IActionResult Index()
    {
        var files = Request.Form.Files;
        //Do something with the files here. 
        return Ok();
    }
    

    2.To upload a file you can also use Multipart content:

            public async Task UploadImageAsync(Stream image, string fileName)
            {
                HttpContent fileStreamContent = new StreamContent(image);
                fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName };
                fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                using (var client = new HttpClient())
                using (var formData = new MultipartFormDataContent())
                {
                    formData.Add(fileStreamContent);
                    var response = await client.PostAsync(url, formData);
                    return response.IsSuccessStatusCode;
                }
             }
    

    3.If you are uploading large files you should consider streaming the files instead, you can read about it here

提交回复
热议问题