Java从服务器下载文件到本地

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/diypp2012/article/details/77897001

我的需求是从服务器端的某磁盘中获取amr文件,并下载。
首先传递的参数strUrl为物理路径,是绝对路径。

//获取文件名,此处看个人如何设计的
String filename = strUrl.substring(strUrl.lastIndexOf("/")+1);
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");

String path = strUrl;
File file = new File(path);
//如果文件不存在
if(!file.exists()){
    return false;
}
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(path);
//创建输出流
OutputStream out = response.getOutputStream();
//缓存区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区中
while((len = in.read(buffer)) > 0){
    out.write(buffer, 0, len);
}
//关闭
in.close();
out.close();        

其次,浏览器端在发起请求时,要使用href指向,如:
window.location.href=’//接口名称’,或<a href='/*接口名称*/'></a>

猜你喜欢

转载自blog.csdn.net/diypp2012/article/details/77897001