繁体   English   中英

将来自asp.net核心的blob数据读取到Angular 7

[英]Read blob data that comes from asp.net core to Angular 7

美好的一天。 请帮助我解决我的问题,我无法正确读取从后端到我的角度的数据。 我在这里所做的是下载来自后端(asp.net核心)的文件

这是我的控制器的代码

[HttpPost("Document")]
public HttpResponseMessage Document()
        {
            try
            {
                var file = Request.Form.Files;

                var fileData = _documentToPdf.DocumentToPdf(file[0].OpenReadStream());
                HttpResponseMessage response = null;


                response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ByteArrayContent(fileData.ToArray())
                };
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = "pdf.pdf";
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentLength = fileData.Length;

                Console.WriteLine("file data size: " + fileData.Length);


                return response;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw;
            }
        }

这是我的角度代码

uploadAndProgress(files: File[]){
    console.log(files)
    var formData = new FormData();
    Array.from(files).forEach(f => formData.append('file',f))

    this.http.post('http://localhost:5000/api/DocumentToPdf/Document', formData, {reportProgress: true, responseType: 'blob',  observe: 'events'})
      .subscribe(event => {
        if (event.type === HttpEventType.UploadProgress) {
          this.percentDone = Math.round(100 * event.loaded / event.total);
        } else if (event instanceof HttpResponse) {
          this.uploadSuccess = true;
          console.log('Success');
          console.log('event: ' + event);
          this.downloadFile(event, 'download.pdf');
        }
    });
  }

  downloadFile(data: any, filename: string) {
    const blob = new Blob([data], { type: 'application/octet-stream' });
    console.log(blob);
    saveAs(blob, filename);
  }

代码Console.WriteLine("file data size: " + fileData.Length); 返回65651但是以angular表示的代码是console.log(blob); 它返回

size: 15
type: "application/octet-stream"

那么为什么它们不相同呢? 因此,我如何正确读取来自asp.net的blob到我的角度,以便我可以下载它。 非常感谢

你可以这样

为您服务

url: string = "some url";

getBlob(): Observable<Blob> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'      
    });
    return this.httpClient.get<Blob>(this.url, {headers: headers, responseType: 'blob' as 'json' });
  }

然后在您的组件中

imageBlobUrl: string = null;

getImage() : void {
    this.blobService.getBlob()
      .subscribe((val) => {
          this.createImageFromBlob(val);
        });
  }
  createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    reader.addEventListener("load", () => {
      this.imageBlobUrl = reader.result;
    }, false);
    if (image) {
      reader.readAsDataURL(image);
    }
  }

然后在您看来

  <img [src]="imageBlobUrl">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM