Upload files and JSON in ASP.NET Core Web API

前端 未结 8 1277
夕颜
夕颜 2020-11-29 18:12

How can I upload a list of files (images) and json data to ASP.NET Core Web API controller using multipart upload?

I can successfully receive a list of files, upload

8条回答
  •  我在风中等你
    2020-11-29 18:37

    Following the excellent answer by @bruno-zell, if you have only one file (I didn't test with an IList) you can also just declare your controller as this :

    public async Task Create([FromForm] CreateParameters parameters, IFormFile file)
    {
        const string filePath = "./Files/";
        if (file.Length > 0)
        {
            using (var stream = new FileStream($"{filePath}{file.FileName}", FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }
    
        // Save CreateParameters properties to database
        var myThing = _mapper.Map(parameters);
    
        myThing.FileName = file.FileName;
    
        _efContext.Things.Add(myThing);
        _efContext.SaveChanges();
    
    
        return Ok(_mapper.Map(myThing));
    }
    

    Then you can use the Postman method shown in Bruno's answer to call your controller.

提交回复
热议问题