// Step 1
function doSubmit(data1, data2){
$("#dataForm").remove();
var form = '';
form += '<form name="dataForm" id="dataForm" action="" target="hiddenIframe" method="post" enctype="multipart/form-data" accept-charset="UTF-8">';
form += '<input type="text" name="data1" id="data1"/>';
form += '<input type="text" name="data2" id="data2"/>';
form += '<div name="dataFormTarget" id="dataFormTarget" style="display:none">';
form += '</div>';
form += '</form>';
$('body').append(form);
$("#dataForm data1").val(data1);
$("#dataForm data2").val(data2);
$("#dataForm").attr("action", "/download/fileDownload.do");
$("#dataForm").submit(function(event){
event.preventDefault();
$.ajax({
url : "/download/fileDownload.do",
async : true,
type : "POST",
data : {
"data1" : data1,
"data2" : data2
},
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
processData : true,
success : function(data){
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="testFile.zip";
link.click();
}
});
});
$("#dataForm").submit();
}
// Step 2
@RequestMapping(value = "/download/fileDownload.do")
public ModelAndView fileDownload(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws Exception {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Parameter inMap = rDictionary(request, response);
Parameter outMap = new Parameter();
Parameter errorMap = new Parameter();
File file = null;
try {
file = new File(inMap.get("data1"));
errorMap = Util.putErrorMap(ErrConst.ERROR_SUCCESS_CODE, null, inMap);
} catch (Exception e) {
e.printStackTrace();
}
mav.addObject("outMap", outMap);
mav = new ModelAndView("downloadView", "downloadFile", file);
return mav;
}
// Step 3
public class DownloadView extends AbstractView {
private static final Logger logger = LogManager.getLogger(DownloadView.class);
public DownloadView() {
setContentType("application/download; charset=utf-8");
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
File file = null;
try{
file = (File) model.get("downloadFile");
response.setContentType(getContentType());
response.setContentLength((int) file.length());
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
OutputStream out = response.getOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
FileCopyUtils.copy(fis, out);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ioe) {
}
}
}
out.flush();
}catch(Exception e){
logger.error("file not found Excpetion !!!["+ file.getPath() +"]");
}
}
}
您好。 我正在尝试使用上面的代码压缩文件下载。 下载完成后,我必须需要回调函数才能下载。
运行此代码时,会发生下载。 但下载的zip文件崩溃了..
我不知道出了什么问题。
请给我解决方案。 感谢。
(对不起,简短的英语。)