我正在尝试下载已通过 id 成功上传到数据库的文件。有谁知道需要做什么才能获得正确的结果?
我有一个 FileUpload 表,其中包含以下列(与文件相关):
Id = uniqueidentifier,
Content = varbinary,
ContentType = nvarchar, e.g. application/pdf
FileName = nvarchar, e.g. filename.pdf
FileType = tinyint
这是控制器中的方法。
/// <summary>
/// Download the file from the database by id.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns>The file.</returns>
[HttpGet]
public async Task<ActionResult> GetDownloadFile(Guid id)
{
if (id == null)
{
throw new UserFriendlyException("File not found.");
}
var file = await _fileUploadRepository.FirstOrDefaultAsync(id);
var filename = file.FileName.ToString();
var fileBytes = file.Content;
return File(fileBytes, file.ContentType,file.FileName);
}
这是试图调用控制器的打字稿,但它不起作用(我只包含了相关代码):
constructor(
injector: Injector,
private _fileUploadsServiceProxy: FileUploadsServiceProxy,
private _notifyService: NotifyService,
private _tokenAuth: TokenAuthServiceProxy,
private _activatedRoute: ActivatedRoute,
private _fileDownloadService: FileDownloadService,
private _searchService: SearchService,
private http: Http
) {
super(injector);
}
/// <summary>
/// Download the file from the database.
/// </summary>
///<param name="file">The file.</param>
downloadFile(file: any): void {
if (file.fileUpload.id) {
var headers = new Headers();
headers.append('Content-Type', file.fileUpload.contentType);
headers.append('Authorization', 'Bearer ' + abp.auth.getToken());
this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${file.fileUpload.id}`, {
headers: headers,
responseType: ResponseContentType.Blob
})
.subscribe(result => {
saveAs(result.blob(), file.fileUpload.fileName);
this.notify.success(`Downloaded ${file.fileUpload.fileName} successfully.`);
});
}
}
您的 C# 代码似乎正确,但您的 TypeScript/Angular 代码不会调用GetDownloadFile
您的 API的操作。
该http.get(...)
方法返回一个 observable 并且只有在您订阅它时才会触发 HTTP 请求。
public downloadFile(id: number): void {
var headers = new Headers();
headers.append('Content-Type', 'application/octetstream');
headers.append('Authorization', 'Bearer ' + abp.auth.getToken());
this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`)
.subscribe(result => {
// result contains your file data.
});
}
现在,您需要保存文件,您可以使用文件保护程序包。
在您的项目根目录(所在package.json
的位置)中使用以下命令安装包
npm install file-saver --save
然后更新您的代码以导入并调用文件保护程序方法来保存您的文件。
import { saveAs } from 'file-saver';
public downloadFile(id: number): void {
var headers = new Headers();
headers.append('Content-Type', 'application/octetstream');
headers.append('Authorization', 'Bearer ' + abp.auth.getToken());
this.http.get(`${AppConsts.remoteServiceBaseUrl}/FileUploadComponents/DownloadFile?id= ${id}`).subscribe(result => {
saveAs(result, 'fileName');
});
}
希望能帮助到你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句