使用MemoryStream和ZipArchive在asp.net Web API中将zip文件返回给客户端 [英] Use MemoryStream and ZipArchive to return zip file to client in asp.net web api

查看:298
本文介绍了使用MemoryStream和ZipArchive在asp.net Web API中将zip文件返回给客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将zip文件从asp.net Web API返回给客户端:

I am trying to return zip file from asp.net web api to client using The following Code:

private byte[] CreateZip(string data)
{
    using (var ms = new MemoryStream())
    {
        using (var ar = new ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            var file = archive.CreateEntry("file.html");

            using (var entryStream = file.Open())
            using (var sw = new StreamWriter(entryStream))
            {
                sw .Write(value);
            }
        }
        return memoryStream.ToArray();
    }
}

public HttpResponseMessage Post([FromBody] string data)
{
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(CreateZip(data));
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip, application/octet-stream");
    return result;
}

运行此代码时,出现以下错误:

When i run this code i get the following error:

ExceptionMessage":值的格式为'application/zip, application/octet-stream'无效."

ExceptionMessage":"The format of value 'application/zip, application/octet-stream' is invalid."

这是JS代码:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  dataType: application/x-www-form-urlencoded
});

任何解释为何会发生这种情况?我真的很希望你能帮到你

Any explanation why this is happen? I would really appriciate your help guys

推荐答案

$.ajax处理文本响应,并将尝试(utf-8)解码内容:您的zip文件不是文本,您将获得损坏的内容. jQuery不支持二进制内容,因此您需要使用链接并在jQuery上添加ajax传输,或直接使用XmlHttpRequest.使用xhr时,您需要设置xhr.responseType = "blob"并从xhr.response斑点中读取.

$.ajax handles text responses and will try to (utf-8) decode the content: your zip file isn't text, you will get a corrupted content. jQuery doesn't support binary content so you need to use this link and add an ajax transport on jQuery or use directly a XmlHttpRequest. With an xhr, you need to set xhr.responseType = "blob" and read from xhr.response the blob.

// with xhr.responseType = "arraybuffer"
var arraybuffer = xhr.response;
var blob = new Blob([arraybuffer], {type:"application/zip"});
saveAs(blob, "example.zip");

// with xhr.responseType = "blob"
var blob = xhr.response;
saveAs(blob, "example.zip");
Edit: examples:

带有 jquery.binarytransport.js (可让您下载Blob或ArrayBuffer即可)

with jquery.binarytransport.js (any library that let you download a Blob or an ArrayBuffer will do)

$.ajax({
  url: url,
  type: "POST",
  contentType: "application/json",
  dataType: "binary", // to use the binary transport
  // responseType:'blob', this is the default
  data: data,
  processData: false,
  success: function (blob) {
    // the result is a blob, we can trigger the download directly
    saveAs(blob, "example.zip");
  }
  // [...]
});

使用原始XMLHttpRequest,您可以看到这个问题,您只需需要添加xhr.responseType = "blob"以获得斑点.

with a raw XMLHttpRequest, you can see this question, you just need to add a xhr.responseType = "blob" to get a blob.

我个人建议您在jQuery上使用ajax传输,这非常简单,您必须下载一个库,将其包含在项目中并编写:dataType: "binary".

I personally recommended you to use an ajax transport on jQuery, that's very easy, you have to download a library, include it in the project and write: dataType: "binary".

这是使用DotNetZip(Ionic.Zip)的API代码:

This is the API code, using DotNetZip (Ionic.Zip):

   [HttpPost]
    public HttpResponseMessage ZipDocs([FromBody] string[] docs)
    {
        using (ZipFile zip = new ZipFile())
        {
            //this code takes an array of documents' paths and Zip them
            zip.AddFiles(docs, false, "");
            return ZipContentResult(zip);
        }
    }

    protected HttpResponseMessage ZipContentResult(ZipFile zipFile)
    {
        var pushStreamContent = new PushStreamContent((stream, content, context) =>
        {
          zipFile.Save(stream);
            stream.Close(); 
        }, "application/zip");

        return new HttpResponseMessage(HttpStatusCode.OK) { Content = pushStreamContent };
    }

这篇关于使用MemoryStream和ZipArchive在asp.net Web API中将zip文件返回给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆