我使用下面的代码来下载文件。我已在 Web api 中成功分配了 bytearray。
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
我使用的完整代码如下
Angular
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;
}
最佳答案
Angular 的 HttpClient 默认假定响应是 JSON。如果 API 的响应是文本字符串,请将 HTTP 请求选项的 responseType
属性(httpService.post
的第三个参数)设置为 “text”
。如果响应是二进制数据,请将响应类型设置为 "arraybuffer"
或 "blob"
。
关于c# - 如何使用 Web api 和 Angular 从字节下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68072420/