文章借鉴:https://blog.csdn.net/zhangzeyuaaa/article/details/52823238
用post请求生成from表单提交请求下载了一下
前台代码:
// post下载,构建from表单以post方式下载
$("#downloadform").remove();
var form = $("<form>");// 定义一个form表单
form.attr("id", "downloadform");
form.attr("style", "display:none");
form.attr("target", "");
form.attr("method", "post");
form.attr("action", contextPath+'/sa/orderformController/downloadOrderShp.do');
var input1 = "<input type='hidden' name='path' value='"+geoJsonPath+"' />";
form.append(input1);
$("body").append(form);// 将表单放置在web中
form.submit();// 表单提交
后台代码:
下载文件的工具类,传要下载的文件路径filePath,文件名称returnName(这个一定要new String转换一下。不然和浏览器编码不同响应到前台会乱码。)。
public static void fileDownload(String filePath, String returnName,
HttpServletResponse response, HttpServletRequest request) throws IOException{
String agent = request.getHeader("User-Agent").toUpperCase();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-type", "application-download");//这个是附件下载 部分文件浏览器会直接读取// 设置响应头,控制浏览器下载文件
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(returnName, "utf-8"));
FileInputStream in1 = new FileInputStream(filePath);
OutputStream out = response.getOutputStream();
byte[] bytes = new byte[5 * 1024];
int len = 0;
while ((len = in1.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
in1.close();
out.close();
out.flush();
}
在粘一处批量压缩文件的工具类
输出流,我是创建了一个FileOutputStream(参数是响应生成的zip格式结尾的压缩包全路径)来使用的。然后就是集合File格式。
public static void writeZipFile(OutputStream ous, List<File> fileList) {
ZipOutputStream zos = new ZipOutputStream(ous);
byte[] buf=new byte[1024];
int readLen = -1;
try{
for(File file : fileList){
ZipEntry ze = new ZipEntry(file.getName());
ze.setSize(file.length());
ze.setTime(file.lastModified());
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(file));
// 读取文件流,写入到zip
while ((readLen = is.read(buf, 0, 1024))!=-1) {
zos.write(buf, 0, readLen);
}
is.close();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
zos.close();
ous.close();
} catch (IOException e) {
}
}
}
压缩文件一定要注意,流的关闭。不然会导致压缩文件下载后,文件虽然可以用,打开压缩包弹出警告框。