java下载导出图片或文件
1.contorller 代码片
.
@GetMapping("download")
public void download(@RequestParam("id") String fileId, HttpServletResponse response) {
OperatorModel operator = this.getOperator();
_IFileService.download(fileId, response,operator.getUserId(), operator.getUserName());
}
imp实现类 代码片
.
@Override
public void download(String fileId, HttpServletResponse response, String operatorId, String operatorName) {
try {
//根据id查询数据
SysFile sysFile = _SysFileMapper.selectById(fileId);
// 文件不存在,响应404
if (sysFile == null) {
this.responseError(response, 404, "文件记录不存在");
return;
}
//把文件路径创建到file中,把file写入到 FileInputStream 输入流中,
//把 文件字节长度给 byte[], 输入流读取到 byte[] 中
byte[] buffer = this.getFileBytes(sysFile);
if (buffer == null || buffer.length == 0) {
this.responseError(response, 404, "物理文件不存在");
return;
}
//输出流
OutputStream os = null;
try {
String contentTypeValue = "application/octet-stream";
if (sysFile.getIsImage() == 1) {
contentTypeValue = "image/" + sysFile.getExtensionName().substring(1);
} else {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sysFile.getFullName(), "UTF-8"));
}
// 设置响应头信息
//response.setHeader("Content-Type", contentTypeValue);
response.setContentType(contentTypeValue);
//定义输出流
os = response.getOutputStream();
//把 输出流写入 字节byte[]中数据
os.write(buffer, 0, buffer.length);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (os != null)
os.close();
}
} catch (Exception ex) {
}
}
private byte[] getFileBytes(SysFile sysFile) {
//文件全路径 :sysFile.getStorePath()
String fullFilename = sysFile.getStorePath();
File file = new File(fullFilename);
if (!file.exists()) {
return null;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
return data;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
前端导出按钮 代码片
.
<el-button
v-access:create
type="primary"
size="small"
@click="exportExcel">导出</el-button>
前端请求方法代码片
.
exportExcel() {
window.location.href="/api/ics/projectPending/toPendingExcel?id=" + this.$route.query.id;
},