从HttpRequestMessage:controller下载zip文件

时间:2021-12-19 09:56:34

I'm working on a web api's using ASP.NET MVC's which download the zip file attached in the HttpRequestMessage

我正在使用ASP.NET MVC开发一个web api,它下载了HttpRequestMessage中附带的zip文件

as below

 var task = this.Request.Content.ReadAsStreamAsync();
            task.Wait();

            if (this.Request.Content.IsMimeMultipartContent())
            {

                using (Stream requestStream = task.Result)
                {
                     // Do not know how to copy the above request to file stream or zip (ionic zip) and generate zip file from it
                 }
            }

note:

1)

using (var fileStream = File.Create("name.zip"))
                        {
                            requestStream.CopyTo(fileStream);
                        }

creates invalid zip..

创建无效的zip ..

2) Zip contains many files inside it.

2)Zip里面包含很多文件。

Waiting for your comments

静候你的评价

Update 1:

 var provider = new MultipartFormDataStreamProvider(ScriptPath);

                Request.Content.ReadAsMultipartAsync(provider);                

                foreach (MultipartFileData file in provider.FileData)
                {

                    Trace.Write(file.Headers.ContentDisposition.FileName);
                   Trace.Write("Server file path: " + ScriptPath);

                }

though does not help me

虽然没有帮助我

1 个解决方案

#1


0  

This works for me. Please treat as pseudo as I didn't compile it. Also you may want to rework the blocking .Result call to take advantage of the Async read.

这对我有用。请视为伪,因为我没有编译它。此外,您可能希望重写阻止.Result调用以利用异步读取。

var requestStream = await Request.Content.ReadAsMultipartAsync();

HttpContent fileContent = requestStream.Contents.SingleOrDefault(c => c.Headers.ContentType != null);

byte[] fileBytes = await fileContent.ReadAsByteArrayAsync();
using (FileStream fs = File.OpenWrite(outputPath))
{
    fs.Write(fileBytes, 0, (int)fileContent.Headers.ContentLength.Value);
}

#1


0  

This works for me. Please treat as pseudo as I didn't compile it. Also you may want to rework the blocking .Result call to take advantage of the Async read.

这对我有用。请视为伪,因为我没有编译它。此外,您可能希望重写阻止.Result调用以利用异步读取。

var requestStream = await Request.Content.ReadAsMultipartAsync();

HttpContent fileContent = requestStream.Contents.SingleOrDefault(c => c.Headers.ContentType != null);

byte[] fileBytes = await fileContent.ReadAsByteArrayAsync();
using (FileStream fs = File.OpenWrite(outputPath))
{
    fs.Write(fileBytes, 0, (int)fileContent.Headers.ContentLength.Value);
}