PDF Javascript Blob中的非UTF-8字符

Mat*_*att 2 pdf blob utf-8 angularjs angularjs-http

我有一个PDF文件,我从WebApi 2应用程序提供给AngularJS客户端.我使用文件保护程序然后将文件保存在客户端上,如下所示(在TypeScript中):

   this.$http.get(`${webUrl}api/pdf?id=${fileDto.id}`)
    .then((response: ng.IHttpPromiseCallbackArg<any>) => {
        var file = new Blob([response.data], { type: 'application/pdf' });
        saveAs(file, 'my.pdf');
    });
Run Code Online (Sandbox Code Playgroud)

我这样做的原因是我可以使用持票人令牌来授权访问PDF(这是通过拦截器添加的).这适用于PDF文件包含非UTF8字符的情况.在后一种情况下,文件仍然会下载,但是当我打开它时,它显示为空白.打开文件我可以看到非UTF8字符被替换为□字符.在JavaScript中,当我检查response.data调试器中的字符串值时,我看到这些字符由represented表示.我是否正确地假设,因为文件是用JavaScript中的字符串编写的,无论我做什么,我都无法正确保存来自JavaScript的非UTF8字符的文件?

geo*_*awg 6

?字符是Unicode替换字符\uFFFD,它在尝试解析非法UTF-8时由UTF-8解析器插入.

PDF文件不是UTF-8字符串; 它们是二进制文件.

要避免从UTF-8到DOMstring(UTF-16)的转换,请将config设置为responseType: 'blob':

   var config = {responseType: 'blob'};

   this.$http.get(`${webUrl}api/pdf?id=${fileDto.id}`, config)
     .then((response: ng.IHttpPromiseCallbackArg<any>) => {
       ?v?a?r? ?f?i?l?e? ?=? ?n?e?w? ?B?l?o?b?(?[?r?e?s?p?o?n?s?e?.?d?a?t?a?]?,? ?{? ?t?y?p?e?:? ?'?a?p?p?l?i?c?a?t?i?o?n?/?p?d?f?'? ?}?)?;            
       var file = response.data;
       saveAs(file, 'my.pdf');
   });
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅