vue+Java 根据网络地址下载文件

发布时间 2023-10-08 14:36:39作者: 菜鸟二小

如下图,当选择某个文件后,再点击下载

image

下载按钮

<img :src="require('@/images/approveperson/download.png')" @click="downloadFile(curFile)">

其中curFile对象如下:
{
    "name": "16782442573331001.png",
    "type": "image",
    "url": "http://119.254.65.194:8088/xb/files/1687326216152.png",
    "uid": 1691546336235,
    "status": "success"
}

点击方法

    downloadFile(curFile) {
      const path = curFile.url;
      downloadCurFile(path).then(res => {
        const url = window.URL.createObjectURL(res)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        const fileName = parseTime(new Date()) + '-' + curFile.name
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    }

前端js

export function downloadCurFile(filePath) {
  return request({
    url: `api/document/download?filePath=` + filePath,
    method: 'get',
    responseType: 'blob'
  })
}

注意:responseType: 'blob'一定要设置上

后端controller

    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void download(String filePath, HttpServletResponse response) {
        documentService.download(filePath, response);
    }

后端service

    @Override
    public void download(String filePath, HttpServletResponse response) {
        try {
            //与服务器建立连接
            URL url = new URL(filePath);
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            try {
                //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
                response.setContentType("multipart/form-data");
            } catch (Exception e){
                e.printStackTrace();
            }
            ServletOutputStream out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            inputStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

下载成功
image
image