如何处理内存流中的文件? [英] How do I process a file from a memory stream?

查看:26
本文介绍了如何处理内存流中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从我的 Vue.js 前端发布一个或多个文件.它是这样做的:

<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">将文件拖到此处开始 <br>或点击浏览</p><p v-if="isSaving">正在上传 {{ fileCount }} 个文件...</p>

</表单>

然后我通过这种方法发布:

函数上传(formData){const url = `${BASE_URL}/api/upload`;返回 axios.post(url, formData, {标题:{'内容类型':'多部分/表单数据'}})}

这似乎可以胜任.

按照 Microsoft 自己的指南,我创建了以下端点:

命名空间 WebApplication6.Controllers{公共类 UploadController :控制器{[HttpPost][路由(/api/上传")]公共异步任务上传文件(列出 文件){长尺寸 = files.Sum(f => f.Length);//临时位置文件的完整路径var filePath = Path.GetTempFileName();foreach(文件中的var formFile){if (formFile.Length > 0){使用 (var stream = new FileStream(filePath, FileMode.Create)){等待 formFile.CopyToAsync(stream);}}}//处理上传的文件 <-- 这意味着什么?如何访问流?返回 Ok(new { count = files.Count, size, filePath });}}}

我对来自 Java 的 C# 有点陌生:Microsoft docs found here 是指处理上传的文件"吗?

如何从内存流中访问它们?为什么在 for 循环之外的评论 - 如果我必须对文件做一些事情,它应该在它上面 - 或者不是?

解决方案

哇,微软的例子太可怕了.

假设您有一个名为 formFileIFormFile(我相信您能够自己编写该循环),获得准系统的最简单方法是:

using (var memoryStream = new MemoryStream()){等待 formFile.CopyToAsync(memoryStream);byte[] bytes = memoryStream.ToArray();//用字节做你想做的事}

您只是将字节复制了两次,在原始表单文件中,在流中,然后到字节数组中,因此当您在 .NET 中有更多经验时,您可能希望对其进行一些优化.也许直接处理内存流而不是字节数组.

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?

解决方案

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.

这篇关于如何处理内存流中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆