在web中下载的方式大多基于servlet,在web.xml中配置下载路径,这里再介绍json(转成base64字符串)和blob的使用方式
servlet
WEB-INF/web.xml
XML
<!--url映射-->
<servlet-mapping>
<servlet-name>DowloadServlet</servlet-name>
<url-pattern>/servlet/dowloadFile</url-pattern>
</servlet-mapping>
<!--指定servlet-->
<servlet>
<servlet-name>DowloadServlet</servlet-name>
<servlet-class>com.xxxxxx.servlet.DowloadServlet</servlet-class>
</servlet>
servlet代码
java
protected void download(String path, String fileName) {
File file = new File(path);
if (!file.exists()) {
logger.error("下载的文件不存在 path=" + path + ",fileName=" + fileName);
}
//下载
OutputStream out = null;
BufferedInputStream in = null;
try {
getResponse().setCharacterEncoding("UTF-8");
getResponse().setContentType("application/vnd.ms-excel");
getResponse().setHeader("Content-Disposition", "attachment; filename=" + fileName);
out = getResponse().getOutputStream();
in = new BufferedInputStream(new FileInputStream(path));
int line;
while ((line = in.read()) != -1) {
out.write(line);
}
} catch (Exception ex) {
logger.error("下载文件失败 path=" + path, ex);
} finally {
if (null != out) {
try {
out.close();
} catch (Exception ex) {
logger.error("关闭out异常 path=" + path, ex);
}
}
if (null != in) {
try {
in.close();
} catch (Exception ex) {
logger.error("关闭in异常 path=" + path, ex);
}
}
}
}
js代码
通过浏览器进行下载
html
<a href="/serlvet/dowloadFile">下载</a>
或者
window.open("/serlvet/dowloadFile")
blob
controller
关键在这响应头:application/octet-stream
java
protected void download(String path, String fileName) {
File file = new File(path);
if (!file.exists()) {
logger.error("下载的文件模板不存在 path=" + path + ",fileName=" + fileName);
}
//下载
OutputStream out = null;
BufferedInputStream in = null;
try {
getResponse().setCharacterEncoding("UTF-8");
getResponse().setContentType("application/octet-stream");
getResponse().setHeader("Content-Disposition", "attachment; filename=" + fileName);
out = getResponse().getOutputStream();
in = new BufferedInputStream(new FileInputStream(path));
int line;
while ((line = in.read()) != -1) {
out.write(line);
}
} catch (Exception ex) {
logger.error("下载文件失败 path=" + path, ex);
} finally {
if (null != out) {
try {
out.close();
} catch (Exception ex) {
logger.error("关闭out异常 path=" + path, ex);
}
}
if (null != in) {
try {
in.close();
} catch (Exception ex) {
logger.error("关闭in异常 path=" + path, ex);
}
}
}
}
js代码[引用博客]
javascript
// 通过后端接口下载文件
function downloadFile() {
// 发起Ajax请求获取文件数据
$.ajax({
url: '/download',
type: 'GET',
dataType: 'binary',
success: function(response) {
// 创建Blob对象
var blob = new Blob([response]);
// 创建URL对象
var url = URL.createObjectURL(blob);
// 创建a标签并设置相关属性
var link = document.createElement('a');
link.href = url;
link.download = 'file.txt';
// 触发点击事件进行下载
link.click();
// 释放URL对象
URL.revokeObjectURL(url);
}
});
}
json
controller
java
public Result execute() throws Exception {
Result result = new Result();
result.setErr_no(0);
try {
String xlsBase64 = xlsToBase64(param.getAbsDownPath(filePath);
DataRow dr = new DataRow();
dr.set("fileName",param.getFileName()+".xlsx");
dr.set("fileBase64Str",xlsBase64);
result.setResult(dr);
}catch (Exception ex){
result.setErr_no(-99);
result.setErr_info("系统错误");
logger.error("模板下载异常", ex);
}
return result;
}
protected String xlsToBase64(String path){
File file = new File(path);
if (!file.exists()) {
logger.error("下载的文件模板不存在 path=" + path );
return null;
}
try{
return Base64Util.encodeBase64String(FileUtils.readFileToByteArray(file));
}catch (Exception e){
logger.error("xls文件转Base64失败 path=" + path, e);
}
return null;
}
javascript 【引用博客】
javascript
var raw = window.atob(data.result.fileBase64Str);
var uInt8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uInt8Array[i] = raw.charCodeAt(i);
}
const link = document.createElement("a");
const blob = new Blob([uInt8Array],{
type: 'application/vnd.ms-excel'
})
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
link.setAttribute('download',data.result.fileName+'.xls');
document.body.appendChild(link)
link.click()
document.body.removeChild(link)