下载压缩文件和下载其他文件的写法是一样的因为都是操作的字节流,通过IO流实现先将文件读取出来,然后再输出到浏览器。
@RestController
public class DownloadController {
@Autowired
private HttpServletResponse response;
@GetMapping("/downloadFile")
public void downloadFile(){
String path = "G:\\document.zip";
File file = new File(path);
if(file.exists()){
String fileName = file.getName();
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
download(response,file);
}
}
public void download(HttpServletResponse response,File file){
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
os.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
bis.close();
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用postman测试就可以了,点击send下面的send and Download就会弹出提示框选择保存文件路径,然后就可以下载文件了。
我们在写这样的代码是有事下载下载的zip文件打卡显示错误,这个问题一般都是在读缓冲区的时候出的问题,仔细分析以这段下代码是否有误,是否能完整输出字节缓冲区的数据。
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
os.write(buffer, 0, len);
}
补充: 如果使用类加载器的方式获取文件名或者文件流对象,需要注意的是pom文件里要添加以下标签,目的是防止zip被idea编译. 否则打开压缩包会出现"不可预料的文件末端"这样的错误.原因是代码在编译时会将我们上传到resources目录下的zip文件也进行编译,导致文件出现错误.
<build>
<plugins>
<plugin>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>zip</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>