Angularプロジェクトでファイルをダウンロードする際に問題があります。問題は、ファイルのURLにナビゲートしようとすると、ファイルが正常にダウンロードされることです。しかし、どのようにAngularでダウンロード機能を実装できますか?AngularとTypeScriptでファイルをダウンロード
[VRoute("PassportAttachments/{id}", 1)]
[HttpGet]
[AllowAnonymous]
public HttpResponseMessage GetPassportAttachmentById(int individualId, [FromUri] int id = -1)
{
try
{
var attachment = _passportAttachmentManager.FindById(id);
string attachmentPath = HttpContext.Current.Server.MapPath(
string.Format(ConfigurationManager.AppSettings["IndividualPassportsPath"], individualId.ToString()) + attachment.FileName);
//string downloadUrl = Url.Content(attachmentPath).Replace("/Api/Contacts/PassportAttachments/~", "");
//var result = new { DownloadUrl = downloadUrl, AttachmentTitle = attachment.Title };
//return Ok(result);
if (File.Exists(attachmentPath))
return new FileContentResult(attachmentPath, attachment.Title, FileResultType.ImageContentResult);
else
return null;
}
catch (Exception ex)
{
Unit.Logger.Error(ex, ToString(), ActionContext.ActionArguments.ToList());
return null;
//return NotFound();
}
}
FileContentResult
コンストラクタ:私が言ったように今
public FileContentResult(string FilePath, string ResponeFileName, FileResultType fileResultType) : base(HttpStatusCode.OK)
{
var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
base.Content = new StreamContent(stream);
base.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachments") { FileName = ResponeFileName };
switch (fileResultType)
{
case FileResultType.ZipContentResult:
base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
break;
case FileResultType.ExcelContentResult:
base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
break;
case FileResultType.PDFContentResult:
base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
break;
case FileResultType.ImageContentResult:
base.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
break;
}
}
、私は自分でファイルをダウンロードするURLを入力すると(それゆえAllowAnonymous
)すべてが正常に動作します。しかし、あなたはContent-Disposition
ヘッダを使用している機能私は活字体
public DownloadAttachments(): void {
if (this.SelectedPassportAttachments != null && this.SelectedPassportAttachments.length > 0) {
if (this.SelectedPassportAttachments.length == 1) {
this.service.DownloadSinglePassportAttachment(this.SelectedPassportAttachments[0].Id, this.IndividualId).subscribe((file: any) => {
// download file (function)
});
}
else {
this.service.DownloadMultiplePassportAttachment(this.IndividualId, this.SelectedPassportAttachments.map(pa => pa.Id), this.SelectedPassportNumber).subscribe();
}
}
}
これは、.csvファイルを生成するときに使用します。 - window.open( "api/controller/get"、 '_self'、 ''); ' – shammelburg