1. 单文件下载
@GetMapping("/showFile")
@ApiOperation("预览文件")
public void showFile(String path, HttpServletResponse response){
File file = new File(path);
if(!file.exists()){
throw new RuntimeException("文件不存在");
}
try(FileInputStream fis = new FileInputStream(file)){
ServletOutputStream os = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(file.getName(), "UTF-8"));
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
//每次写出1Mb
byte[] data = new byte[1 << 30];
int len = 0;
//6.通过response对象获取OutputStream流
//7.将FileInputStream流写入到buffer缓冲区
while ((len = fis.read(data)) > 0) {
//8.使用OutputStream将缓冲区的数据输出到客户端浏览器
os.write(data, 0, len);
}
}catch (Throwable e){
e.printStackTrace();
throw new RuntimeException("查询文件失败");
}
}
2.多文件打包下载
代码中使用的 HttpRequest 工具类使用的是 hutool的工具包,使用前请先引用
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.1.0</version> </dependency>
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import cn.hutool.http.HttpRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public void downloadAttachments(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("附件.zip", "UTF-8"));
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
List<String> fileUrls = new ArrayList<>();
fileUrls.add("http://xxx.com/file/1.jpg");
try(ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())){
for (String fileUrl : fileUrls) {
InputStream inputStream = HttpRequest.get(fileUrl)
.execute()
.bodyStream();
String fileName = fileUrl.substring(fileUrl.lastIndexOf(File.separator) + 1);
zos.putNextEntry(new ZipEntry(fileName));
int len;
// 读入需要下载的文件的内容,打包到zip文件
byte[] buffer = new byte[1 << 30];
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
inputStream.close();
}
}catch(Exception e){
e.printStackTrace();
}
}