springBoot+vue实现二进制文件流下载

private static void downLoadExcel( String fileName, HttpServletResponse response,
Workbook workbook) {
try {
response.setCharacterEncoding(“UTF-8”);
response.setHeader(“content-Type”, “multipart/form-data”);
response.setHeader(“Content-Disposition”,
“attachment;filename=” + URLEncoder.encode(fileName, “UTF-8”));
workbook.write(response.getOutputStream());

	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}

方法二:

	  @ApiOperation(value = "计算接口对应的下载")
    @GetMapping("downloadcalculate")
    public ResponseCode<String> downloadcalculate(@RequestParam String name, HttpServletResponse response){
//HVAC分体空调与设备清单EDS2011-新风处理空调(c8de6658-acf6-452c-9e5a-363f04eb8c64).xlsx
//        String  filePath =System.getProperty("user.dir")+"\\File\\FileTemplate\\HVAC分体空调与设备清单EDS2011-新风处理空调("+uuid +").xlsx";
        String  filePath =System.getProperty("user.dir")+"\\File\\FileTemplate\\"+name;
        File file=new File(filePath);
        String fn = name;
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(file);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name,"utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            os.write(buffer);
        } catch (Exception e) {


            e.printStackTrace();
         return    ResponseCode.error(e.getMessage());
        }


        return ResponseCode.sucess();
    }

法三:
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@CrossOrigin
@ApiOperation(value = “计算接口对应的下载”)
@GetMapping(“downloadcalculate”)
public ResponseEntity downloadcalculate(String name) throws IOException {

FileSystemResource file = new FileSystemResource(System.getProperty("user.dir")+"\\File\\FileTemplate\\"+name);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");

return ResponseEntity
        .ok()
        .headers(headers)
        .contentLength(file.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .body(new InputStreamResource(file.getInputStream()));

}

标题前端接收:

方式一(GET)

window.open(process.env.VUE_APP_FILE_API + ‘/masterComputingModule/Update/downLoadcalculateResult?projectId=’ + id, ‘_self’)

方式二(post)

axios({
method: ‘get’,
url: process.env.VUE_APP_FILE_API + ‘/masterComputingModule/Update/downLoadcalculateResult?projectId=’ + id,
responseType: ‘arraybuffer’
}).then(res => {
const name = res.headers[‘content-disposition’]
console.log(name.split(“attachment;filename*=utf-8’”)[1])
if (res.size === 0) { // 如果返回是空的
this.$message({
message: ‘报错了’,
type: ‘warning’
})
} else { // 返回不为空
if (!!window.ActiveXObject || ‘ActiveXObject’ in window) {
window.navigator.msSaveOrOpenBlob(res, ‘计算结果.xlsx’)
} else {
const url = window.URL.createObjectURL(

          new Blob([res.data], {

            type: 'application/octet-stream'
          })

        )

        const link = document.createElement('a')

        link.href = url

        link.setAttribute(

          'download', decodeURI(name.split("attachment;filename*=utf-8''")[1], 'utf-8')

        )

        link.click()
      }
    }
  })
  此处对应的前台部分重要代码:(不这样写前台拿不到响应头中的文件名),如果出现跨域问题给接口方法加个@CrossOrigin
     response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 后端实现文件下载 在Spring Boot中,我们可以使用以下代码实现文件下载: ```java @GetMapping("/download") public ResponseEntity<Resource> downloadFile() throws IOException { Resource resource = new UrlResource("file:/path/to/file"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\""); return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource); } ``` 其中,`UrlResource`是Spring提供的获取文件资源的类,`HttpHeaders.CONTENT_DISPOSITION`设置文件下载方式为附件,`MediaType.APPLICATION_OCTET_STREAM`指定文件类型为二进制。 2. 前端实现文件下载Vue中,我们可以使用Element UI中的`el-button`组件来实现文件下载: ```html <el-button type="primary" icon="el-icon-download" @click="downloadFile">下载文件</el-button> ``` 在Vue组件中,我们需要定义`downloadFile`方法来实现文件下载: ```javascript downloadFile() { window.location.href = '/download'; } ``` 其中,`window.location.href`将页面重定向到下载链接,即后端实现文件下载接口。 需要注意的是,如果需要传递参数给后端,可以使用axios或者fetch来发送GET或POST请求,将参数传递给后端,再在后端实现文件下载。具体实现方法可以参考以下代码: ```javascript downloadFile() { axios.get('/download', { params: { filename: 'example.txt' }, responseType: 'blob' }).then(response => { const blob = new Blob([response.data], {type: 'application/octet-stream'}) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'example.txt' link.click() window.URL.revokeObjectURL(url) }) } ``` 在这个例子中,我们使用了axios来发送GET请求,`params`中传递了参数filename,`responseType`设置返回类型为二进制。在请求成功后,我们将返回的数据转换为Blob对象,通过URL.createObjectURL方法生成下载链接,然后创建一个a标签并设置download属性,模拟点击a标签来下载文件。最后使用URL.revokeObjectURL方法释放资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值