簡體   English   中英

下載來自 Java REST API in ZC31C335EF372813C451B18BA0DD3

[英]Download .doc that comes from a Java REST API in Angular

問題是從angular java接收ResponseEntity時,它接收為Blob,但它下載的Word不正確,它是一個帶有正確File所在路徑的Word

    private aFile() {
    this.rest.aFile(this.formData)
      .subscribe(res => {
        this.contenidoFile = res;

        var blob = new Blob([this.contenidoFile], { type: 'application/octet-stream' });

     saveAs(blob, "createdocument.doc");

      }, (err) => {
        console.error(err);
        alert('Ha habido un error');
      });
  }

 aFile(formData: FormData) {
    return this.http.post(PATH_FILE, formData, {
      responseType:'blob'
    });
  }

Java中的代碼:

 @PostMapping("/file")
    public ResponseEntity<File> docFileV1(
        @RequestParam("file") MultipartFile originalFile) {

        return ResponseEntity.ok(docService.processDocFile(originalDocFile));

    }

例如原始 Word 的文本將是“你好,這是一個 word 文檔”,而不是 angular 下載的 Word 文檔的文本是
"C:\var\tmp\DocWork\bcc272d8-fdac-4384-97bc-1fdc5dd5736b\document.doc"

也就是說,我要下載的word轉換成word的路徑,怎么下載原來的word而不是它的路徑呢?

嘗試如下,我用 .net 核心后端測試它

是console.log 打印響應屬性,如'response.body'?

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class FileService {

  constructor(private http: HttpClient) {
  }

  get(url: string) { 

    const formData = {};
    return this.download(url, formData)
      .subscribe((response) => {

        console.log(response);

        let file = new Blob([response.body], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});

        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          const name = "test";
          window.navigator.msSaveOrOpenBlob(file, name);
        } else {
          const fileUrl = URL.createObjectURL(file);
          const child = window.open(fileUrl);
        }
      });
  }

  download(url: string, formData): Observable<any> {
    const requestOptions : any = {
        observe: "response",
        responseType: "blob",           
        headers: new HttpHeaders({
          "Accept": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        })
    };
    const request = new Request(requestOptions);
    return this.http.post(url, formData, requestOptions);
  }
}

嘗試使用此代碼下載文件而不是使用saveAs

 var blob = new Blob([this.contenidoFile], { type: 'application/octet-stream' });
const e = document.createEvent("MouseEvents"),
      a = document.createElement("a");
    a.download = "data.docx";
    a.href = window.URL.createObjectURL(blob);
    a.dataset.downloadurl = ["application/octet-stream", a.download, a.href].join(":");
    e.initEvent("click", true, false);
    a.dispatchEvent(e);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM