どう表現したらいいのかわかりづらいですが、インターネット上にあるファイルをブラウザでダウンロードしようとするとブラウザのダウンロード履歴画面で進捗が表示され、途中でキャンセルなどの制御ができるかと思います。
そのような処理をAngularで実現したいのですが、データが全部受信されるまで応答がなくなり、終わったらファイルがいきなりブラウザのダウンロード履歴画面に現れるような状態です。すぐにダウンロードが開始されるようにするにはどうしたら良いでしょうか?
以下がそのコードです。
downolad(param: { [key: string]: string }) {
const fileName = 'ファイル名';
const dataParams = new HttpParams({ fromObject: param });
this.http.get('WebAPIアドレス', { params: dataParams, responseType: 'blob' }).subscribe((data:any) =>{
const blob = new Blob([data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
};
前提として、API側も自身で作っており、ファイル自体はAmason S3にあるので、そこから引っ張ってきている状態です。
このAPIはAmazon S3 からファイルを直接ダウンロードするようなWebAPIはどのように作れば良いか?で作成したものになります。
以下がそのコードです。
[Route("download/s3")]
[HttpGet]
public IHttpActionResult GetS3Data(string key)
{
// データベースにアクセスし、keyからバケット名、ダウンロード元パス、ダウンロード先パスを取得
IAmazonS3 client = new AmazonS3Client(RegionEndpoint.USEast2);
GetBucketLocationRequest request1 = new GetBucketLocationRequest
{
BucketName = バケット名
};
// リージョン取得
string location = client.GetBucketLocation(request1).Location.Value;
client = new AmazonS3Client(RegionEndpoint.GetBySystemName(location));
using(var transferUtility = new TransferUtility(client))
{
var stream = transferUtility.OpenStream(bucketName, filePath);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "testfile.zip"
};
result.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;
}