r3p*_*ica 6 c# file-upload asp.net-web-api
我正在尝试创建一个控制器,允许我将图像保存到我的数据库中.到目前为止,我有一些代码:
/// <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);
}
}
Run Code Online (Sandbox Code Playgroud)
但它没有用.当我进入使用块时,我收到一条错误消息:
"将内容复制到流时出错."
"无法访问已关闭的文件."
有谁知道为什么?
发生这种情况的原因是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);
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用非常小的文件,您可以使用:
这会将文件数据存储在内存中,并且应该按预期工作.请注意,如果您使用大文件(25mb +),则首先要流式传输到磁盘,否则可能会出现内存不足,因为.net会尝试将整个文件保存在内存中.