我正在尝试创建一个控制器,允许我将图像保存到我的数据库中.到目前为止,我有一些代码:
/// <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); } }
但它没有用.
当我进入使用块时,我收到一条错误消息:
“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);
此外,如果您使用非常小的文件,您可以使用:
这会将文件数据存储在内存中,并且应该按预期工作.但是,如果您正在使用大文件(25mb),请先警告它首先流式传输到磁盘,否则您可能会出现内存异常,因为.net会尝试将整个文件保存在内存中.