我有一个 REST API 端点,它接收 .Net Core 1.1 上的 zip 文件.我从这样的请求中获取 IFormFile
I have a REST API endpoint which receives zip file on .Net Core 1.1. I'm getting IFormFile from request like this
var zipFile = HttpContext.Request.Form.Files.FirstOrDefault();然后我需要将它传递给不支持 IFormFile 的 .Net Standard 1.5 的服务方法.
And then I need to pass it to service method from .Net Standard 1.5, where IFormFile is not supported.
所以问题是:如何将 IFormFile 转换为 ZipFile 或标准 1.5 支持的其他类型,或者可能有一些更合适的方法来操作 zip 文件?谢谢!
So the question is: how can I convert IFormFile to ZipFile or to some other type which is supported in Standard 1.5, or maybe there is some more proper way to operate with zip files? Thanks!
推荐答案IFormFile 只是接收文件的包装器.您仍然应该阅读实际文件对其进行处理.例如,您可以将文件流读入一个字节数组并将其传递给服务:
IFormFile is just a wrapper for the received file. You should still read the actual file do something about it. For example, you could read the file stream into a byte array and pass that to the service:
byte[] fileData; using (var stream = new MemoryStream((int)file.Length)) { file.CopyTo(stream); fileData = stream.ToArray(); }或者您可以将流复制到文件系统中的物理文件中.
Or you could copy the stream into a physical file in the file system instead.
但这基本上取决于您实际想要对上传的文件做什么,所以您应该从那个方向开始并将IFormFile 转换为您需要的内容.
But it basically depends on what you actually want to do with the uploaded file, so you should start from that direction and the convert the IFormFile into the thing you need.
如果您想以 ZIP 格式打开文件并从中提取某些内容,您可以尝试 ZipArchive 构造函数 接受一个流.像这样:
If you want to open the file as a ZIP and extract something from it, you could try the ZipArchive constructor that takes a stream. Something like this:
using (var stream = file.OpenReadStream()) using (var archive = new ZipArchive(stream)) { var innerFile = archive.GetEntry("foo.txt"); // do something with the inner file }更多推荐
C# IFormFile 作为 ZipFile
发布评论