代码之家  ›  专栏  ›  技术社区  ›  INDRAJITH EKANAYAKE

Angular6:下载文档文件

  •  0
  • INDRAJITH EKANAYAKE  · 技术社区  · 5 年前

    在我的项目中,我想下载系统生成的文档文件。因此,在Springboot后端,我编写了控制器类,将请求发送到前端,

     @RequestMapping(value = "/downloadDocument/{docId}", method = RequestMethod.GET)
        public void downloadDocument(@PathVariable("docId") Integer docId, HttpServletResponse response) {
    
    
            log.debug("downloadDocument docId"  + docId);
             try {
                 ProjectDocument projectDocument = docRepo.findById(docId);
                 InputStream is = new ByteArrayInputStream(projectDocument.getDocument());
                 response.setHeader("Content-Disposition", "attachment; filename=" + projectDocument.getFileName());
                 IOUtils.copy(is, response.getOutputStream());
    
                    response.flushBuffer();
    
            } catch (IOException ex) {
                 log.error(ex);
                throw new RuntimeException("IOError writing file to output stream");
            }
    
        }
    

    在我的前端,我不知道要发送什么 HttpServletResponce 进入后端。所以我想知道的是,

    1 必须发送吗 HttpServletResponse 从前端?。如果可以,我应该发送什么 HttpServletResponse ?

    2 这有什么用 HttpServletResponse 在这里

    1 回复  |  直到 5 年前
        1
  •  2
  •   Adrita Sharma    5 年前

    你可以用 file-saver

    还加上 { responseType: 'blob' } http get请求中的as选项

    getGenaratedLetterTemplate(userId): Observable<any> {
      console.log(userId);
      return this.http.get<any>(this.apiUrl + 'getGeneratedLetter/' + userId,  { responseType: 'blob' });
    }
    

    组成部分:

    import saveAs from 'file-saver';

      getGenaratedLetterTemplate(userId).subscribe((resp: any) => {
        saveAs(resp, `data.docx`)
      });