使用Angular下载.xls文件:JSON.parse(< anonymous>)位置0的JSON中的意外令牌P [英] Download .xls file using Angular: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>)

查看:98
本文介绍了使用Angular下载.xls文件:JSON.parse(< anonymous>)位置0的JSON中的意外令牌P的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下服务器方法,用于为存储在Azure Blob Storage中的xls文档返回byte[].

I have the following server method for returning an byte[] for an xls document stored in Azure Blob Storage.

[FunctionName("ReadBatchFile")]
        public async static Task<HttpResponseMessage> ReadBatchFile([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Agreements/ReadBatchFile")]HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var fileName = req.GetQueryNameValuePairs()
                   .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                   .Value;
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(await AzureHelpers.ReadFromBlobStorage(fileName));  //returns byte[] 
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return response;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                req.CreateResponse(HttpStatusCode.InternalServerError);
            }
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }

从上面可以看出,response.Content被设置为ByteArrayContent,而我的contentType被设置为application/octet-stream.

As can be seen from the above, the response.Content is set an ByteArrayContent and my contentType is application/octet-stream.

Angular中,我在服务中具有以下方法来调用上述功能.

In Angular, I have the following method in my service to call the above function.

readBatchFile(fileName: string): Observable<Blob> {
    let endpoint = environment.endpoints.agreement.baseUrl + environment.endpoints.agreement.readBatchFile + "&fileName=" + fileName;
    const httpOptions = {
      headers: new HttpHeaders({ contentType: 'application/octet-stream' })}; //application/vnd.ms-excel   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    return this.http.get<Blob>(endpoint, httpOptions);
  }

尽管我指定contentTypeapplication/octet-stream,并且我的get方法应返回Blob类型,但仍然出现以下错误:

Although I am specifying that the contentType is application/octet-stream, and that my get method should return a Blob type, I still get the following error:

JSON中的意外令牌P在JSON.parse的位置0↵ ()

Unexpected token P in JSON at position 0↵ at JSON.parse ()

为什么Angular仍将服务器的响应视为JSON?

Why is Angular still seeing the response from the server as JSON?

更新

这是我的请求标头:

Accept: application/json, text/plain, */*
Authorization: Bearer ...
Origin: http://localhost:4200
Referer: http://localhost:4200/batches
responseType: application/octet-stream
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36

响应标题:

Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Disposition: attachment; filename=B4debe034-efc6-416f-8082-422a4122a857_MTN_Upgrade_20181017_T065548.xls
Content-Length: 3011
Content-Type: application/octet-stream
Date: Wed, 17 Oct 2018 06:55:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET

响应:

PKø6QMäH­¯3[Content_Types].xmlµÏJ1Æ_eÉU´D¤ÛªU°>ÀÌvCóÌ´¶oo6+"¥z$ßÌ÷ý3_¼köÉÆÐÆM+ÞÖ[ÑC0àbÀVÄr1_RSfµ¢gNwJîÑÉ0¥ÙkÞ¨zT×ÓéÒ10ðà!ó{ì`ç¸Yïu+ %g5pÁRÅL4"Ã]ýanÌ    ÌäDftµzèê4 ¨4$<ÉÖà¿"b×Y&ê/#RF0Ô#²w²VéÁ1ô2?/®êàÔGÌÛ÷·²j"êù·ü*ªevAâ£C:G1*î!£yå\ü<ÁÏoU~ñ   PKäH­¯3PKø6QMÚë®'_rels/.relsÏÁ0àWYzc1ájðæVÖe
oïb<xlú÷ûÓ²^æ=Ѭ"Ë¡U¤kÜÚËî,DiµÈ¢ÔUyÅIÆtúÁô1ºçAõ8ËC6ùYÆ4zÃT£4È÷y~àþÓ­É-À7ºÖ®ÿ±©ëgRmüQñH²ô£eâ/òãhÌ
¼*ùæÁê
PKÚë®'PKø6QMæl($×Sxl/workbook.xmlO½NÄ0~È;ÂpBUÛ`9    é{Hkt]9)åÝx$^ôª
F&ö÷cûûó«9|Ä ÞQgjávWB²Ü{:·0ews®Y.oÌUÔjiaÈy¬µNvÀhÒG¤Â9hriå¬Ù9oñí²¾«ª½&Miðc5í?Yi4}skT4 k«^=Îé÷È¥Uºkôîjݪ"±$Muûò>(©}rì^26£5Á>rSèÍêXTÛêîPKæl($×SPKø6QMb¢Ö4xl/_rels/workbook.xml.rels­ÏjÃ0_Åè¾8é`Q·1èµ@ØJØÆÒÚåík6VR(cdôý>¬åúkÔ2÷1hª]:ýÇÓ+(ÈÀDëÕrKJYaß'VØIoZ³õ4"W1Q(/mÌ#Jis§Ú#v¤uý¢ó·LµqòÆ5 öS¢ÿ°cÛöÞ£ý)È}ùÈH
sGbà:bý]ªPAßY<ReÊ_^M~ú¿âï1ÛI.[ÌÇ¿2úæÚ«PKb¢Ö4PKø6QMÄΫhïxl/worksheets/sheet1.xmlËr0F_a_Ðýâ±Iã:ñ®ÓE»¦¶äpwë¢ÔW¨ÀÄ7 Ðù~I
ðïÏßùÃG~Þ±.!@¨b«wYñºOåþó³6o6Uª^ØYiYgql·©Êé£*\ß^<)Ý¥yõ~mÕJoO¹*ÊÀb£Ié²iv´á¥Ú=µìѨdWO!?\JåIVËù.sÕ«ÙFíá#mHÄËy
ÿÌÔÙÞ´j%¿µ~«.6»Ej6öàu=øwìÔ>9Êúü¢²×´thÙê­AUê O>êó9Û©k¡!Â\ÇödKÿjºÃø&8jã<J±LFã¸ãÛÑ!Å  $ÆI'·q! ¥
Î)<mâôÇe!8ÀÑÑ8kâìÀ
/³Ñ8oâüg#&¥ «M\\ã p½Clâò§nòHp¡tÒñeóÔ;mÉrnô90U¯+]5q[oO·ã¬»û¾óø½6ÄW]âÉ'PXùîß|tµOÐ.ñì¬K¼øï-;{­BÔ*D^DöúìY~@zWH-c    "$§C"z6§«­ÞS{@zíezeQ¤£·Jñ¤Rð }¥ø~¥ÓÕÖH_éÒW:½²Í(ÒQJZ¥dR©OxJ¾Rr¿Òéj뤯té+^Ùf¹(oÞ£©ûMPf­u©Lýeo]ÿPKÄΫhïPKø6QM"tÛ4SÎ
xl/styles.xmlR½nà ~ÄÞGjUU¶3T²Ô%K:tÅ6ØHp ÀÝWëÐGê+°8Q¥Lw|þ~ð?_ßù~TuBC³Í#nt<xÆû2w~ìØ3æQà+pï½y!Ä5=SÔm´a¾pmõáh;âe´uQ¤$Ùm·ODQ¸ÌaPò5z_àIÊk¸@üNT$K, ÍÀ+¢¶"¡dæ¦âRHy¶Úá(sC½gªp@Kÿ>V`ÐÀD¼Cï,²ÝãZJH®µmÃ,׿1Ce.÷QaEקÆkK­½×*v­ *ïliwä<Æ=|ð«£y omeÂÒF£µl6¹£§ÆÈé0¨Ù*­3ÒÖ®PéYF~vÎI©WQgÅ=øýåÊ£ôþ»~0mG~óhÈåa¿PK"tÛ4SÎPKø6QMPùûxl/sharedStrings.xmlm]k0ÿJÈ}h][Z2è2Ðþ ÇfsÛ¿_ÆØÖË<ÏÄ=±wp8Zð`/9ÓØv4}ÂoõóîÌ2­¬rvIcDbþªÁDó£Ø îíÆÎ:­È]/pv ZHO"ò(´
g]ù²gßÈþ/1¦1¥Eu­ò2ÆâüÐêZ°Ò®ijÇ2ÛÂRtÇ^TóªzØÌÿºZ¹±ë6#O
ù¥1¾o$h×¾¨Kû¥mñÌj
píä)ÑÃñt^WdT6p åNkq{§þ!ü¦_PKPùûPK-ø6QMäH­¯3[Content_Types].xmlPK-ø6QMÚë®'Y_rels/.relsPK-ø6QMæl($×S@xl/workbook.xmlPK-ø6QMb¢Ö4Txl/_rels/workbook.xml.relsPK-ø6QMÄΫhïrxl/worksheets/sheet1.xmlPK-ø6QM"tÛ4SÎ
 xl/styles.xmlPK-ø6QMPùû®xl/sharedStrings.xmlPKÂë   

推荐答案

您可以像这样直接在get-request中设置responseType:

You can set the responseType in the get-request directly like this:

return this.http.get<Blob>(endpoint, { reponseType: 'application/octet-stream'});

更多信息位于文档中的此处.

More information is here in the docs.

您的content-type标头仅用于请求标头,不会影响响应.

Your content-type header is only used for the request-header, it does not influence the response.

这篇关于使用Angular下载.xls文件:JSON.parse(&lt; anonymous&gt;)位置0的JSON中的意外令牌P的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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