How do I process a file from a memory stream?

随声附和 提交于 2021-01-29 11:02:12

问题


I am posting one or more files from my Vue.js frontend. It's being done as such:

<form enctype="multipart/form-data" novalidate v-if="isInitial || isSaving">
    <div class="dropbox">
        <input type="file" multiple :name="uploadFieldName" :disabled="isSaving" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length" accept=".json" class="input-file">
        <p v-if="isInitial">
            Drag files here to begin <br> or click to browse
        </p>
        <p v-if="isSaving">
            Uploading {{ fileCount }} files...
        </p>
    </div>
</form>

I then post it via this method:

function upload(formData) {
    const url = `${BASE_URL}/api/upload`;
    return axios.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
          }
    })
}

Which seems to do the job.

Following Microsoft's own guide, I have created the following endpoint:

namespace WebApplication6.Controllers
{
    public class UploadController : Controller
    {
        [HttpPost]
        [Route("/api/upload")]
        public async Task<IActionResult> UploadFiles(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 <-- What does this entail? How do I access the stream?

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

I am somewhat new to C# coming from Java: What does the Microsoft docs found here mean when they say "process uploaded files"?

How do I access them from the memory stream? Why is the comment outside the for loop - if I had to do stuff with the files, it should be on it - or not?


回答1:


Wow that Microsoft example is horrible.

Assuming you have a single IFormFile named formFile (I trust you be able to write that loop yourself), the simplest way to get to the barebones is:

using (var memoryStream = new MemoryStream())
{
    await formFile.CopyToAsync(memoryStream);
    byte[] bytes = memoryStream.ToArray();

    // do what you want with the bytes
}

You just copied the bytes twice, in the original formfile, in the stream and then into the byte array, so when you have more experience in .NET you may want to optimize it a bit. Maybe proceed your processing with the memory stream directly instead of the byte array.




回答2:


It appears the Microsoft docs may be a bit misleading.

foreach (var formFile in files)
{
    if (formFile.Length > 0)
    {
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await formFile.CopyToAsync(stream);
            // here you have access to each individual file
        }
    }
}

Inside the using statement, you can manipulate the stream object, i.e. save it out to its unique file path, process data within the file (if a .csv), etc. The question is a bit broad but the Microsoft article may be a bit misleading to you.



来源:https://stackoverflow.com/questions/51517482/how-do-i-process-a-file-from-a-memory-stream

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