5

I got a C# .NET Core Web API (REST). I want to implement an endpoint for upload files and one for download files (any file type, as binary). What is best practice for design and code? What I find so far by a search engine is kind of week. Do you have a recommendation for me? I guess I have to save metadata like the title (type,..?) somewhere else. Could make it easier to search for files.

At this link from microsoft I get the problem, that it seems to be only for MVC API, what I don't use.

After

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)

files is empty.

And this from the c-sharpcorner does not work neater. My object file from Type IFormFile doesn't know the method.GetFilename().

enter image description here

jps
  • 20,041
  • 15
  • 75
  • 79
Frank Mehlhop
  • 1,480
  • 4
  • 25
  • 48

2 Answers2

3

If you take a look at the IFormFile docs, you'll notice, that it has a property FileName, which you can use:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile?view=aspnetcore-2.2

So, as an example, you could take that and save it whereever you want with that property. In my case all the low level stuff of writing that file to the storage is hidden in a repository, but you get the idea:

public async Task<IActionResult> Upload(IFormFile file)
{
    if (file == null || file.Length == 0) return BadRequest();
    using (var ms = new MemoryStream())
    {
        file.CopyTo(ms);
        var img = new Entities.Image
        {
            Name = file.FileName,
            ContentType = file.ContentType,
            Data = ms.ToArray()

         };
         await _repo.CreateImage(img);
         return Ok();
    }
}
Marco
  • 22,856
  • 9
  • 75
  • 124
3

There is very nice article about how to upload / download files using .net core at this location. The same tutorial should work for web API also.

I checked in your question that it is not working for you, you many want to check the request through postman / fiddler and check if data is being sent properly. This blog has example of file upload web API

For getting the filename, the definition of IFormFile as as below:

public interface IFormFile
{
    string ContentType { get; }
    string ContentDisposition { get; }
    IHeaderDictionary Headers { get; }
    long Length { get; }
    string Name { get; }
    string FileName { get; }
    Stream OpenReadStream();
    void CopyTo(Stream target);
    Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

Hence you should be able to use property FileName to get the file name.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37