[英]Create FileStream in memory instead of saving a physical file on disk
I am uploading a file to an api, and I have to copy my requestStream to a FileStream in order to post the file to the API. 我正在将文件上传到api,并且必须将我的requestStream复制到FileStream才能将文件发布到API。 My code below works, but I have to save the file to a temp folder to create the FileStream, and then I have to clean up the temp folder again after the operation.
下面的代码可以工作,但是我必须将文件保存到temp文件夹中以创建FileStream,然后在操作后必须再次清理temp文件夹。 Is there a cleaner way of doing that - eg creating the FileStream in memory (if that's possible) instead of saving it to the disk?
有没有一种更清洁的方法-例如在内存中创建FileStream(如果可能的话)而不是将其保存到磁盘上?
Stream requestStream = await Request.Content.ReadAsStreamAsync();
//Create filestream by making a temporary physical file
using (FileStream fileStream = System.IO.File.Create(@"C:\tempFolder\" fileName))
{
await requestStream.CopyToAsync(fileStream);
var postedFile = ms.CreateMedia(fileName, folder.Id, "file");
postedFile.SetValue("umbracoFile", fileName, fileStream);
ms.Save(postedFile);
}
// Clean up
if ((System.IO.File.Exists(@"C:\tempFolder\" + fileName)))
{
System.IO.File.Delete(@"C:\tempFolder\" + fileName);
}
Why not use the requestStream
directly? 为什么不直接使用
requestStream
? It is an instance of Stream
and your API end point expects an instance of Stream
, there is no need to copy the content of requestStream
to any intermediary point unless you want to add unnecessary overhead. 它是
Stream
一个实例,并且您的API端点需要一个Stream
的实例,除非您想要添加不必要的开销,否则无需将requestStream
的内容复制到任何中间点。
Stream requestStream = await Request.Content.ReadAsStreamAsync();
var postedFile = ms.CreateMedia(fileName, folder.Id, "file");
postedFile.SetValue("umbracoFile", fileName, requestStream);
ms.Save(postedFile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.