java接收ios文件路径_02vue+axios+form实现文件下载(附Java实现代码)

参考文章

1.0前端实现思路

用一个from接收后台返回的文件流。form用display为none隐藏;其中form构造action属性,属性值为后台文件下载的参数。同样可以用display为none的input插入form中,input可以携带参数,后台可以用@requestParam接收。

前端具体代码如下:

Document

new Vue({

el: '#app',

data: {

files: []

},

methods: {

handlerClick: function () {

//自定义form标签,初始化相关参数

var form = document.createElement("form");

var access_token = "1756467474";

form.setAttribute("style",

"display:none");

form.setAttribute("method", "get");

var params = {};

params.Authorization = access_token;

form.setAttribute("header",

params);

var path =

'E:\\_ex_workplace\\zxsbWeb\\esgov-zxsb-zxsbweb\\src\\pages\\selfDetection.vue';

var input = document.createElement('input');

input.setAttribute('type', 'hidden');

input.setAttribute('name', 'path');

input.setAttribute('value', path);

form.append(input);

form.setAttribute("action",

"http://127.0.0.1:8778/download"

);

form.setAttribute("target", "_blank");

var body = document.createElement("body");

body.setAttribute("style", "display:none");

document.body.appendChild(form);

form.submit();

form.remove();

}

}

02.java代码实现

后端Java代码实现首先将文件读入到数组buffer中,然后用response获取输出流,输出流将buffer写出即可。

@GetMapping("/download")

public void download(@RequestParam("path") String path, HttpServletResponse response) {

System.out.println(path);

try {

// path是指欲下载的文件的路径。

File file = new File(path);

// 取得文件名。

String filename = file.getName();

// 取得文件的后缀名。

String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

// 以流的形式下载文件。

InputStream fis;

fis = new BufferedInputStream(new FileInputStream(path));

byte[] buffer = new byte[fis.available()];

fis.read(buffer);

fis.close();

// 清空response

response.reset();

// 设置response的Header

response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));

response.addHeader("Content-Length", "" + file.length());

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());

response.setContentType("application/octet-stream");

toClient.write(buffer);

toClient.flush();

toClient.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值