Upload Multipart / form-data file to asp.net core web api

How to make uploading files with multiple files in asp.net core web api? Is it possible to POST both JSON and the image at the same time in one POST?

+9
source share
2 answers

Update-.net core 2.0 +

With the .net core, you can use the new IFormFile interface to load both the image and properties in a single post. For instance:

 [HttpPost("content/upload-image")] public async Task<IActionResult> UploadImage(MyFile upload) 

The MyFile class might look like this:

 public class MyFile { public string userId { get; set; } public IFormFile File { get; set; } // Other properties } 

You can access properties and file as follows:

 var file = upload.File // This is the IFormFile file var param = upload.userId // param 

To save / save the file to disk, you can do the following:

 using (var stream = new FileStream(path, FileMode.Create)) { await file.File.CopyToAsync(stream); } 

.NET Framework

Yes it. Depending on the client platform you are using, you can configure your web API for Content Type-Multipart , and then do something like:

 [HttpPost] [Route("content/upload-image")] public async Task<HttpResponseMessage> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // enter code here } 

Define and configure the directory in which your image will be saved.

 var root = HttpContext.Current.Server.MapPath("~/Content/Images/"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } 

Install StreamProvider and try to get the model data that you mentioned in JSON format .

 var streamProvider = new MultipartFormDataStreamProvider(root); var result = await Request.Content.ReadAsMultipartAsync(streamProvider); if (result.FormData["model"] == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); } 

Now access the files in the request.

 try { // Deserialize model data to your own DTO var model = result.FormData["model"]; var formDto = JsonConvert .DeserializeObject<MyDto>(model, new IsoDateTimeConverter()); var files = result.FileData.ToList(); if (files != null) { foreach (var file in files) { // Do anything with the file(s) } } } 
+12
source

Yes, it is possible for POST and JSON, and images simultaneously in the same POST request. Here is the solution: https://dottutorials.net/dotnet-core-web-api-multipart-form-data-upload-file/

0
source

Source: https://habr.com/ru/post/1267263/


All Articles