Angular的HttpClient假设respose默认为JSON。如果来自API的响应是文本字符串,请将HTTP请求选项的
我使用以下代码下载文件。我已经成功地在web api中分配了字节数组。
byte[] bytes = llResponse.FileContent;
response.Content = new ByteArrayContent(bytes)
但最终我得到了以下响应我的浏览器控制台
SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:36098:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:9462:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:99246:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:9461:60) at Zone.runTask (http://localhost:4200/polyfills.js:9239:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:9536:34) at invokeTask (http://localhost:4200/polyfills.js:10674:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:10711:21)
message: "Unexpected token � in JSON at position 0
我使用的完整代码如下
角度
this.appService.DownloadFile(this.filter).subscribe((data) => {
importedSaveAs(data, this.filter.FileName)
})
public DownloadFile(obj:liveLinkFilter): Observable<any> {
var url = this.baseApiUrl + 'RadioLink/DownloadFile';
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.httpService.post(url, obj, { headers: reqHeader, withCredentials: true });
}
Web Api代码
[HttpPost]
[Route("DownloadFile")]
public HttpResponseMessage DownloadFile(LiveLinkDocumentBO obj)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
LLAccessResponse llResponse;
//GetFileType(lvlnkBo.FileName);
LLService llservice = new LLService();
llResponse = llservice.FetchDocument(Convert.ToInt32(obj.FileId), obj.LLUserName, obj.FileName);
//Read the File into a Byte Array.
byte[] bytes = llResponse.FileContent;
response.Content = new ByteArrayContent(bytes);
//Set the Response Content Length.
response.Content.Headers.ContentLength = bytes.LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = obj.FileName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(obj.FileName));
return response;
}
responseType
属性(httpService.post
的第三个参数(设置为"text"
。如果响应是二进制数据,请将响应类型设置为"arraybuffer"
或"blob"
。