您的位置:首页 > 编程语言 > Java开发

【java用I/O流下载】给个url就能下载,可复制粘贴直接使用

2017-10-10 14:37 344 查看
项目中源代码如下:
@RequestMapping("downloadattr")
@ResponseBody
public void downloadattr(HttpServletRequest request, HttpServletResponse response) {
//服务器中文件的路径
String url = request.getParameter("url");
String[] fullName = url.split("/");
//本次代码的url用"/"分割后最后一段是文件名
String attaName = fullName[fullName.length - 1];
attaName.substring(14, attaName.length());
try {
//设置编码为utf-8
String filePath = java.net.URLDecoder.decode(url, "UTF-8");
// 读取临时文件并写出
File file = new File(filePath);
if (file.exists()) {
InputStream in = new FileInputStream(file);
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-disposition", "attachment; filename=" + attaName);
response.setContentType("application/msword");

OutputStream outWrite = response.getOutputStream();
// 一次读多个字节
byte[] tempBytes = new byte[100];
int byteRead = 0;
// 读入多个字节到字节数组中,byteRead为一次读入的字节数
while ((byteRead = in.read(tempBytes)) != -1) {
outWrite.write(tempBytes, 0, byteRead);
}
in.close();
outWrite.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
主要内容为try-catch里面的,可以复制粘贴,改改地址和文件名字就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐