WebAPI文件上传-无需将文件写入磁盘 [英] WebAPI File Uploading - Without writing files to disk
问题描述
有关处理使用FormData上传到ASP.NET WebAPI处理程序的文件的所有文档/教程/问题,均使用MultipartFormDataStreamProvider
处理多部分流以将其拆分为相关的表单字段和文件.
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.
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.
当我只能使用HttpContext.Current.Request.Files[0].InputStream
直接在内存中访问给定的文件流时,似乎很麻烦.
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.
WebAPI如何直接访问文件流而无需使用MultipartFormDataStreamProvider
的IO开销?
How can WebAPI just access the file stream directly without the IO overhead of using MultipartFormDataStreamProvider
?
官方教程: http://www.asp .net/web-api/overview/advanced/sending-html-form-data,-part-2
推荐答案
已解决:
使用现有的简单 MultipartMemoryStreamProvider
.不需要自定义类或提供程序.这与重复问题不同,该问题通过编写解决方案定制提供商.
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.
然后按如下方式在WebAPI处理程序中使用它:
Then use it in a WebAPI handler as so:
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();
}
}
这篇关于WebAPI文件上传-无需将文件写入磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!