美文网首页
下载文件

下载文件

作者: buenos_dan | 来源:发表于2020-05-22 10:56 被阅读0次
    1. restController的工作
      1. 首先读取文件
      File file = new File(filePath, fileName)
      InputStream inputStream = new FileInputStream(file);
      
      1. 设置response
      response.setContentType("application/msword;charset=utf-8");
      response.setHeader("Content-Disposition", "attachment");
      
      1. 写到输出流
      @GetMapping(value = "/download/userguide")
      public StreamingResponseBody getDocument(HttpServletResponse response) {
      //read file
      ...
      //set response
      ...
      //write to outputStream
      return outputStream -> {
          int nRead;
          byte[] data = new byte[1024];
          while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
          outputStream.write(data, 0, nRead);
          }
      };
      
    1. response.setContentType()的作用及参数
      response.setContentType(MIME)的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
      具体文件类型对应的参数,可以参考下面链接
      https://blog.csdn.net/luman1991/article/details/53423305

    2. 前端下载文件
      将button的click响应汉书

    <button type="button" (click)="downloadUserguide()" label="下载模板"></button>
    
     downloadUserguide(){
            console.log("download user guide");
            const link: HTMLElement = document.createElement('a');
            link.setAttribute('href', SERVER_API_URL + 'uaa/api/download/userguide');
            link.setAttribute('download', 'CPE-UserGuide.docx');
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    

    相关文章

      网友评论

          本文标题:下载文件

          本文链接:https://www.haomeiwen.com/subject/uhafahtx.html