C# IFormFile as ZipFile

可紊 提交于 2019-12-24 18:31:13

问题


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();

And then I need to pass it to service method from .Net Standard 1.5, where IFormFile is not supported.

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!


回答1:


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.

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.


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
}


来源:https://stackoverflow.com/questions/46220025/c-sharp-iformfile-as-zipfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!