【问题标题】:Opening a file with C# as a BLOB, and downloading with JS as a BLOB用C#作为BLOB打开文件,用JS作为BLOB下载
【发布时间】:2017-08-02 07:54:10
【问题描述】:

我的 .NET Core 服务器上有一个 PDF,我需要以某种方式将其作为 BLOB 通过网络发送,以便我的 JS AJAX 请求可以将其转换回 PDF,以便下载。

间接的原因是因为文件来自我的API,只能通过AJAX访问。由于需要不记名令牌,我不能只在幕后使用表单,因为创建的站点没有 cookie。 (很奇怪,我知道,但目前就是这样,我不打算改变那部分)

所以,在我的 C# 方面,我尝试了几种变体,如下所示。 ApiResponse 只是我使用的一个容器,其中包含一个 bool 和一个 string(名为 message),因此我可以判断请求是否正确。

这些都是我一直在尝试的

return new ApiResponse(true, File.ReadAllText(path));
return new ApiResponse(true, Convert.ToBase64String(File.ReadAllBytes(path)));
return new ApiResponse(true, JsonConvert.SerializeObject(File.ReadAllBytes(path)));

在 JS 方面,以相同的顺序解析它,我有:

// Get the response in object form, since it's sent as an ApiResponse
const response = JSON.parse(xmlhttp.response);

const text = response.message;
const text = atob(response.message)
const text = JSON.parse(response.message)

我也尝试过

const text = atob(JSON.parse(response.message))

然后,我正在这样做:

const blob = new Blob([text], {type: "application/pdf"});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "file.pdf";

document.body.appendChild(a);
a.click();

这确实会正确生成已下载的文件。但是,该文件无效:它已损坏。

我几乎被困在这一点上,而且我无法找到使用这种方法从头到尾使用 Javascript 下载文件的东西。它要么是背面,要么是正面,但从不系在一起。

那么,我怎样才能成功地通过网络发送 PDF BLOB,并在前端重新创建它以便下载?

【问题讨论】:

    标签: javascript c# ajax download blob


    【解决方案1】:

    如何进行转换的简单答案是不要

    每个现代浏览器都原生支持 base64 编码,因此在下载之前无需将数据转换回 BLOB。

    因此,结束代码为:

    const a = document.createElement("a");
    a.href = "data:application/pdf;base64," + response.message;
    a.download = "file.pdf";
    
    document.body.appendChild(a);
    a.click();
    

    【讨论】:

      猜你喜欢
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2016-06-14
      • 2015-03-27
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多