gpt4 book ai didi

c# - 如何正确地将文件从 ASP.NET Core 下载到 Angular?

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:53 25 4
gpt4 key购买 nike

我在服务器上有一个文件要发送给客户端:

[HttpPost]
public IActionResult Test()
{
byte[] bytes = System.IO.File.ReadAllBytes(Path.Combine(FilesFolder, "test.docx"));
return File(bytes, _contentTypeWord);
}

我也试过

return PhysicalFile(pathUploadFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

在客户端我接受使用:

private _downloadFile(data: ArrayBuffer, fileName: string, contentType: string) {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);

var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

public test() {
this.http.post("Diplom/Test", { }, {
headers: this.headers(),
}).subscribe(
result => {
this._downloadFile(result.arrayBuffer(), "test.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
},
error => {
alert("Не удалось отредактировать файл");
console.error(JSON.stringify(error));
})
}

客户端收到的文件已损坏且无法打开。服务器上的文件很好,可以完美打开。生成的文件仍然无法打开,甚至重量增加了 2 倍(在服务器上为 487 KB,而客户端有 925 KB)。

最佳答案

您可以使用文件结果,只需提供一个将返回 FileContentResult 的 api 链接。 .

public IActionResult Download(// some parameter) 
{
// get the file and convert it into a bytearray
var locatedFile = ....
return new FileContentResult(locatedFile, new
MediaTypeHeaderValue("application/octet"))
{
FileDownloadName = "SomeFileDownloadName.someExtensions"
};
}

现在你只需要提供链接,浏览器就会知道如何处理它。那就不用自己动手了。

编辑:我刚刚用 Angular Testing 了这种方法,使用 Angular 时需要执行以下操作来下载文件 HttpClient .

首先你需要通过 npm 安装 file-saver。

npm i --save file-saver

然后在您的模块中导入并包含 HttpClientModule

import { HttpClientModule } from '@angular/common/http';
...
@NgModule({
imports: [
HttpClientModule
...
]
...
})

现在继续您的服务并执行以下操作

import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';

@Injectable()
export class MyFileService {

public constructor(private http: HttpClient) {}

public downloadFile() {
this.http.get('my-api-url', { responseType: 'blob' }).subscribe(blob => {
saveAs(blob, 'SomeFileDownloadName.someExtensions', {
type: 'text/plain;charset=windows-1252' // --> or whatever you need here
});
});
}

然后处理 blob 并创建一个文件保存对话框。

关于c# - 如何正确地将文件从 ASP.NET Core 下载到 Angular?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com