WebAPI文件上传——不需要将文件写入磁盘。

时间:2021-10-17 02:32:08

All the documentation / tutorials / questions about processing a file uploaded using FormData to a ASP.NET WebAPI handler use MultipartFormDataStreamProvider to process the multipart stream to split it into the relevant form fields and files.

所有关于处理文件的文档/教程/问题都是使用FormData上传至ASP。NET WebAPI处理程序使用MultipartFormDataStreamProvider来处理多部分流,将其分割成相关的表单字段和文件。

var root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

await Request.Content.ReadAsMultipartAsync(provider);

foreach (MultipartFileData file in provider.FileData)
{
   // File
}

However, the files are automatically written to a directory during processsing.

但是,在处理过程中,文件会自动写入目录。

It seems a lot of hassle when I could just use HttpContext.Current.Request.Files[0].InputStream to access a given file stream directly in memory.

当我可以使用HttpContext.Current.Request.Files[0]时,似乎有很多麻烦。InputStream直接访问内存中的给定文件流。

How can WebAPI just access the file stream directly without the IO overhead of using MultipartFormDataStreamProvider?

如果没有使用MultipartFormDataStreamProvider的IO开销,WebAPI怎么能直接访问文件流呢?

Official tutorial: http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2

官方教程:http://www.asp.net/web-api/overview/advanced/sending-html-form-data,第2部分

1 个解决方案

#1


75  

Solved:

解决:

Use the existing simple MultipartMemoryStreamProvider. No custom classes or providers required. This differers from the duplicate question which solved the solution by writing a custom provider.

使用现有的简单的MultipartMemoryStreamProvider。不需要自定义类或提供程序。这与通过编写自定义提供程序解决方案的重复问题不同。

Then use it in a WebAPI handler as so:

然后在WebAPI处理程序中使用:

public async Task<IHttpActionResult> UploadFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return StatusCode(HttpStatusCode.UnsupportedMediaType);
    }        

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

    foreach (var stream in filesReadToProvider.Contents)
    {
        var fileBytes = await stream.ReadAsByteArrayAsync();
    }
}

#1


75  

Solved:

解决:

Use the existing simple MultipartMemoryStreamProvider. No custom classes or providers required. This differers from the duplicate question which solved the solution by writing a custom provider.

使用现有的简单的MultipartMemoryStreamProvider。不需要自定义类或提供程序。这与通过编写自定义提供程序解决方案的重复问题不同。

Then use it in a WebAPI handler as so:

然后在WebAPI处理程序中使用:

public async Task<IHttpActionResult> UploadFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return StatusCode(HttpStatusCode.UnsupportedMediaType);
    }        

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

    foreach (var stream in filesReadToProvider.Contents)
    {
        var fileBytes = await stream.ReadAsByteArrayAsync();
    }
}