将 excel 文件导入"Unexpected token P in JSON at position 0"错误



我在c#和angular中使用webapi项目我在控制器中实现了一个导出excel文件的函数,在angular服务中实现了另一个导入excel文件的函数。

c#函数工作得很好,它创建了一个新的excel,并将其保存到某个路径。

问题发生在angular:在位置0的JSON中意外的token p

下面是我的代码: c#控制器:

[HttpGet]
[Route("downloadProducts/{userID}")]
public HttpResponseMessage DownloadProducts(int userID)
{
var pathToExcel=WriteExcel.GetPathToProducts(userID);
var buffer = File.ReadAllBytes(pathToExcel);
var stream = new MemoryStream(buffer);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.ToArray())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "products.xlsx"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}

角服务:

downloadFile (userID:number):Observable<Blob>{
return this.http.get<Blob>(`${this.url}/downloadProducts/${userID}`);
}

Componenet。TS

const EXCEL_TYPE = 'application/octet-stream';
this.productsService.downloadloadFile(this.user.userID).subscribe(data=>{
var file = new Blob([data], { type: EXCEL_TYPE });
this.href =   window.URL.createObjectURL(file);
setTimeout(() => {
console.log(this.href);
}, 500);
window.open(this.href);
})

我应该修复什么?

谢谢你。

在上述函数中使用MIME类型text/csv代替application/octet-stream它可以使用。xlsx扩展名下载文件。

不要将其转换为Blob try。

downloadFile (userID:number):Observable<any>{
return this.http.get<any>(`${this.url}/downloadProducts/${userID}`);
}

相关内容

最新更新