下载文件的几种方式:
1、流下载
//入参
HttpServletResponse response;
//打开文件流
InputStream is = new FileInputStream(path);
//设置响应头和下载文件名
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream os = new response.getOutputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) > 0) {
os.write(b, 0, length);
}
//关闭流
os.close();
is.close();
2、下载网络文件
URL url = new URL(urlPath);
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
//本地保存路径
FileOutputStream fs = new FileOutputStream(localPath);
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = inStream.read(b)) > 0) {
fs.write(b, 0, length);
}
fs.close();
inStream.close();
3、在线打开和下载
File file = new File(filePath);
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
OutputStream os = new response.getOutputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = br.read(b)) > 0) {
os.write(b, 0, length);
}
//关闭流
os.close();
br.close();