Submitting multiple files to ASP.NET controller accepting an ICollection<IFormFile>

落爺英雄遲暮 提交于 2019-11-30 15:32:32

问题


In my ASP.NET Core backend, I have a controller function that looks like this:

[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> UploadFile(ICollection<IFormFile> files)
{
   ...
}

In my front-end, I call the function like this:

var postSettings = {
    method: 'POST',
    credentials: 'include',
    mode: 'cors'
}
uploadDocuments( files ) {
    var data = new FormData();
    data.append('files', files);   
    postSettings.body = data;

    return fetch(endPoint + '/documents/upload', postSettings);
}

If "files" is a single file - not an array with one file, but a single File object - UploadFile is called with an ICollection<IFormFile> containing the single file.

If "files" is a list of files, either a FileList or an array of File objects, UploadFile is called with an empty ICollection<IFormFile>.

How do I submit a list of files in such a way that they can be parsed as an ICollection<IFormFile>?


回答1:


Reference Uploading multiple files at once - with Fetch

uploadDocuments(endPoint, files) {
    var postSettings = {
        method: 'POST',
        credentials: 'include',
        mode: 'cors'
    };
    var data = new FormData();
    if(files.length > 1) {
        for(var x = 0; x < files.length; x++) {
            data.append('file' + x, files.item(x));    
        }
    } else {
        data.append('files', files);   
    }
    postSettings.body = data;

    return fetch(endPoint + '/documents/upload', postSettings);
}

Reference Uploading small files with model binding

When uploading files using model binding and the IFormFile interface, the action method can accept either a single IFormFile or an IEnumerable<IFormFile> (or List<IFormFile>) representing several files. The following example loops through one or more uploaded files, saves them to the local file system, and returns the total number and size of files uploaded.

[HttpPost]
[Route("documents/upload")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}


来源:https://stackoverflow.com/questions/43455994/submitting-multiple-files-to-asp-net-controller-accepting-an-icollectioniformfi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!