上传到内存流时无法访问已关闭的文件

Cannot access a closed file when uploading to memory stream

我正在尝试创建一个允许我将图像保存到我的数据库中的控制器。到目前为止,我有这段代码:

/// <summary>
/// Handles an upload
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Upload()
{

    // If the request is not of multipart content, then return a bad request
    if (!Request.Content.IsMimeMultipartContent())
        return BadRequest("Your form must be of type multipartcontent.");

    // Get our provider
    var provider = new MultipartFormDataStreamProvider(ConfigurationManager.AppSettings["UploadFolder"]);

    // Upload our file
    await Request.Content.ReadAsMultipartAsync(provider);

    // Get our file
    var file = provider.Contents.First();
    var bytes = await file.ReadAsByteArrayAsync();

    // Using a MemoryStream
    using (var stream = new MemoryStream(bytes))
    {

        stream.Seek(0, SeekOrigin.Begin);

        // Create the data
        var data = "data:image/gif;base64," + Convert.ToBase64String(stream.ToArray());

        // Return the data
        return Ok(data);
    }
}

但它不起作用。 当我进入 using 块时,我收到一条错误消息:

"Error while copying content to a stream."
"Cannot access a closed file."

有人知道为什么吗?

发生这种情况的原因是 MultipartFormDataStreamProvider 在将上传的数据写入您将其传递给构造函数时提供的文件位置后关闭并处理上传的文件流:ConfigurationManager.AppSettings["UploadFolder"]

要访问已上传的文件,您需要从上传的文件位置查阅磁盘上的文件数据:

所以在你的例子中你的代码需要使用这个:

// Read the first file from the file data collection:
var fileupload = provider.FileData.First;

// Get the temp name and path that MultipartFormDataStreamProvider used to save the file as:
var temppath = fileupload.LocalFileName;

// Now read the file's data from the temp location.
var bytes = File.ReadAllBytes(temppath);

此外,如果您使用非常小的文件,您可以改用:

MultipartMemoryStreamProvider

这会将文件数据存储在内存中,应该会按预期工作。请注意,如果您使用的是大文件 (25mb+),最好先流式传输到磁盘,否则您可能会遇到内存不足的异常,因为 .net 会尝试将整个文件保存在内存中。