还是直接贴代码
/**
* 为了复用
* @param response
* @param name
* @param src
* @param clType
*/
@ResponseBody
@PostMapping("downloadWs")
public void download(HttpServletResponse response, String name,String src,String clType) {
if (name != null) {
InputStream is = null;
BufferedInputStream bs = null;
OutputStream os = null;
try {
byte[] cl=null;
if(WsCommonConsts.DOWNLOAD_DZJZ.equals(clType)) {
cl=getDzjzcl(src);
}else{
cl=downloadFromFtp(src);
}
if (cl!=null) {
// 设置Headers
response.setHeader("Content-Type", "application/octet-stream");
// 设置下载的文件的名称-该方式已解决中文乱码问题
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1"));
is = new ByteArrayInputStream(cl);
bs = new BufferedInputStream(is);
os = response.getOutputStream();
byte[] buffer = new byte[cl.length];
int len = 0;
while ((len = bs.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
}
} catch (IOException ex) {
LoggerUtil.error("下载文书或材料异常", ex);
} finally {
try {
if (is != null) {
is.close();
}
if (bs != null) {
bs.close();
}
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
LoggerUtil.error("关闭流异常", e);
}
}
}
}
/**
* 根据路径获取文件流
* @param ftp 大文件对象
* @return
*/
public byte[] downloadFromFtp(String ftp) {
String protocol=getURLDecoderString(ftp);
String attributes=protocol.substring(protocol.indexOf("attributes") + "attributes".length() + 1, protocol.lastIndexOf(']'));
Map<String, String> properties=new HashMap<>();
String[] attrs = attributes.split(",");
for(int i=0;i<attrs.length;i++) {
String[] item=attrs[i].split(":");
if(item.length>1) {
properties.put(item[0], item[1]);
}
}
byte[] bs=FtpClientUtil.download(MapUtils.getString(properties, "_path").replaceAll("\\\\","/"), MapUtils.getString(properties, "_file_name"));
return bs;
}
这里对大对象数据进行了解析
<form method="post" name="downloadForm" action="common/wsCommon/downloadWs" target="rfFrame">
<input type="hidden" name="name" id="fileName">
<input type="hidden" name="src" id="fileSrc">
<input type="hidden" name="clType" id="clType">
</form>
<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe>
form是为了能使用post请求,因为使用get的话又需要重新编解码,而且当时没想到需要从request.getQueryString()中获取请求的参数(还没找到原因,框架为SpringBoot,get请求只有用request.getQueryString()才获取得到参数)。
这里为了阻止页面跳转,将form的target属性设置为页面中的iframe
xzWs: function(item, e) {
document.getElementById("fileName").value = item.name;
document.getElementById("fileSrc").value = item.src;
document.getElementById("clType").value = item.type;
document.downloadForm.target = "rfFrame";
document.downloadForm.submit();
}
以上,一个适配众多浏览器的简单下载功能实现了