[英]Download .doc file from angular
我是 angular 的新手,我正在嘗試在單擊按鈕時創建一個下載鏈接以下載 doc 文件。 該文件已成功下載,但里面的內容是“[object Object]”。 文件路徑在我的 webroot 中,我正在訪問這樣的文件:
[Route("api/[Controller]")]
[ApiController]
public class DownloadController : Controller
{
private readonly IWebHostEnvironment _env;
public DownloadController(IWebHostEnvironment env)
{
_env = env;
}
[HttpGet]
public async Task<IActionResult> Download()
{
string filePath = Path.Combine(_env.WebRootPath, "Image\\CV.doc");
using MemoryStream memorystream = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memorystream);
}
memorystream.Position = 0;
return File(memorystream, "application/msword", "CV.doc");
}
}
我的共享服務.ts。 我也將觀察更改為“身體”。
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
cvFilePathURL = "https://localhost:44346/api/Download";
constructor(private http: HttpClient) { }
getCV(): Observable<any> {
return this.http.get(this.cvFilePathURL, {
observe: 'response',
responseType: 'text'
});
}
}
這是我的 componenet.ts
import { Component } from '@angular/core';
import { SharedService } from 'src/app/shared.service';
@Component({
selector: 'app-nav-menu',
templateUrl: './nav-menu.component.html',
styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
constructor(private service: SharedService) { }
isExpanded = false;
collapse() {
this.isExpanded = false;
}
toggle() {
this.isExpanded = !this.isExpanded;
}
public Download(): void {
this.service.getCV().subscribe((data) => {
var newBlob = new Blob([data], { type: "application/msword" });
//For Internet Explorer
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
return window.navigator.msSaveOrOpenBlob(newBlob);
}
//For other browsers:
//Create a link pointing to the ObjectURL containing the blob.
const mainData = window.URL.createObjectURL(newBlob);
var link = document.createElement('a');
link.href = mainData;
link.download = "CV.doc";
link.click();;
});
}
}
目標框架 - asp.net 核心 3.1 Angular Cli - 11.0.6 更新:所以我設法下載了具有 [objects Objects] 以外的實際內容的文件。 但是,該文件充滿了特殊字符,長達 206 頁。 原始文件只有 2 頁長。
我認為您可能需要在代碼中進行一些更改,或者您可以查看我將在下面提供的代碼。
優CONTROLLER
[HttpPost]
[Route("get-download-file")]
public HttpResponseMessage GetDownloadFile(dynamic data)
{
// var localFilePath = HttpContext.Current.Server.MapPath("~/Documents/" + (string)data.fileName);
var localFilePath = HttpContext.Current.Server.MapPath((string)data.mappingPath);
string contentType = MimeMapping.GetMimeMapping(Path.GetExtension(localFilePath));
HttpResponseMessage response = null;
try
{
if (!File.Exists(localFilePath))
{
//if file not found than return response as resource not present
response = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
//if file present than read file
var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
//compose response and include file as content in it
response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(fStream)
};
//set content header of reponse as file attached in reponse
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(fStream.Name)
};
//set the content header content type as application/octet-stream as it returning file as reponse
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
}
}
catch (Exception ex)
{
return response;
}
return response;
}
在您的 Service(Angular) 中添加 httpPostMethod:
public httpPostFile(url: string, body: any): Observable<Blob> {
return this.httpClient.post<Blob>(this.baseUri + url, body, { responseType: 'blob' as 'json' })
.pipe(
catchError(this.handleClientError)
);
}
最后,您必須從 angular 調用該方法。 使用下面的代碼->
let tempBlob: any;
let contentFileType= 'txt'; //you can make that file type dynamic using some addional code.
const data = {
fileName: this.fileName,
mappingPath: '~/Documents/' + this.fileName
};
this.apiService.httpPostFile('download/get-download-file/', data)
.subscribe(fileData => {
tempBlob = new Blob([fileData], { type: contentFileType });
},
(error) => {
}, () => {
const blob: Blob = new Blob(tempBlob, { type: contentFileType });
const fileName: string = this.filedlName;
const objectUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
a.href = objectUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
});
注意:在 angular 和 ASP MVC Web API 中可以有更有效的方法來下載文件。 但這種方式對我有用。 你可以試試。 如果您發現任何困難,請隨時提出。 謝謝你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.