文件下载输出成zip文件:
1、前端整个按钮,调js方法:(参数:param,需要下载的id,用逗号拼接)
var param = "?dto.id=";//需要自己拼接param
window.location.href = "<%=basePath%>app/upload/fileAction!uploadFileToZip.do" + param;
2、java关键依赖
<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.9.6</version></dependency>
3、后端代码:
import org.apache.tools.zip.ZipEntry; //zip的关键包
import org.apache.tools.zip.ZipOutputStream;//zip的关键包@Controller
@RequestMapping("/app/upload")
public class FileAction {//下载zip文件@RequestMapping("fileAction!uploadFileToZip.do")public void uploadFileToZip() {ParamDTO dto = getDto();//页面参数,可以用自己的方法try {String[] param = dto.getAsString("id").split(",");//参数Map<String, String> m = new HashMap<String, String>();String zipName = getNowDate()+ ".zip";//zip名称,我用的是当前日期//下载压缩文件代码getResponse().reset();getResponse().setContentType("application/x-download");getResponse().setHeader("Content-Disposition", "attachment;fileName=" + new String(zipName.getBytes("GB2312"), "iso8859-1"));ZipOutputStream zipout = new ZipOutputStream(getResponse().getOutputStream());UserAccountInfo userAccountInfo = getUserAccountInfo(dto.getUserInfo());// // 获取用户信息,自己定义InputStream input = null;for (String s : param) {m.put("yvk010", s);List<Map> fjList = getDao().queryForList("vk01shenhe.queryApplyList_publish_fjxz", m);//查询需要下载的附件list,自己根据需求查询if (!ValidateUtil.isEmpty(fjList)) {Object yuf054 = fjList.get(0).get("yuf054");if (!ValidateUtil.isEmpty(yuf054)) {String filename = "未命名";//读文件//input = new ByteArrayInputStream(domains.get(0).getOrig_file());input = UcmUtil.getFile(yuf054.toString(), userAccountInfo);//去文件服务器读取文件流,自己定义byte[] buffer = new byte[input.available()];int len = input.read(buffer);if (len < 0) {}filename = (String) fjList.get(0).get("yuf052");zipout.putNextEntry(new ZipEntry(filename));//设置压缩文件内的字符编码,不然会变成乱码zipout.setEncoding("GBK");zipout.write(buffer);}}}if (input != null) {input.close();}if (zipout != null) {zipout.closeEntry();zipout.close();}} catch (Exception e) {}}//生成当前日期方法public String getNowDate(){LocalDate today = LocalDate.now(); // 获取当前日期DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义日期格式String formattedDate = today.format(formatter); // 格式化日期System.out.println(formattedDate); // 输出格式化后的日期return formattedDate;}
}
4、效果图:
查询数据库,循环查询去服务器查询文件流,这里就不写了,每个公司情况不一样,自己套公式!
如果文件过多,可以自己分批下载,看情况舔砖就行!