一、上传文件前端代码,以layui前端组件upload为例:
渲染上传按钮
<button type="button" class="layui-btn" id="uploadDemo">选择文件</button>
做动画加载控制
<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="uploadConfirm()">确认上传</button>
文件名显示占位
<div id="fielName" ></div>
下载点击链接,excel-template-01为数据库记录具体的主键id
<a href="javascript:void(0)" onclick="exportExcel('excel-template-01')" >下载最新报价单</a>
upload.render({//上传样本信息单
elem: '#uploadDemo'
, url: path + '/demo/uploadFile.do'
, auto: false //选择文件后不自动上传
, bindAction: '#uploadConfirm' //指向一个按钮触发上传
, accept: 'file' //普通文件
, data: {
channelType: 1
}
, choose: function (obj) {
var files = this.files = obj.pushFile();
//读取本地文件
obj.preview(function (index, file, result) {
$("#fielName").html(file.name);
})
}
, done: function (res) {
if (res.success) {
layer.closeAll();
} else {
layer.msg(res.message);
layer.close(loadingIndex)
}
}
});
function uploadConfirm() {
loadingIndex = layer.load(1, {
shade: [0.5,'#000'] //0.1透明度的背景
});
}
window.exportExcel=function (id) {
downloadExcel(path + '/demo/exportExcel.do',"id",id);
}
function downloadExcel(actionPath,paramName,list,paramName2,data) {
if(list.length>0 || parseInt(list).toString() != "NaN"){
var $eleForm = $("<form type='hidden' method='post' id='tempFrom'>" +
"<input type='hidden' id='"+paramName+"' value='" + list + "' name='"+paramName+"' type='text' />" +
"<input type='hidden' id='"+paramName2+"' value='" + data + "' name='"+paramName2+"' type='text' />" +
"</form>");
console.log($eleForm)
$eleForm.attr("action", actionPath);
$(document.body).append($eleForm);
//提交表单,实现下载
$eleForm.submit();
$("#tempFrom").remove();//移除表单
}else return false;
}
二、上传文件后端代码,将文件转换为二进制存入数据库
@Controller
@RequestMapping("demo")
public class FileUtilController {
@Autowired
ExcelDataMapper excelDataMapper;
@RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST)
@ResponseBody
public Result uploadQuotationFile(@RequestParam(value = "file", required = false) MultipartFile mfile) {
String fileName = mfile.getOriginalFilename();
long size = mfile.getSize();
File file = null;
try {
if (mfile.equals("") || mfile.getSize() <= 0) {
mfile = null;
} else {
InputStream ins = mfile.getInputStream();
file = new File(mfile.getOriginalFilename());
//拿到文件
getInputStream(ins, file);
ins.close();
}
} catch (IOException e) {
e.printStackTrace();
}
//文件转换成二进制,入库
FileInputStream fis = new FileInputStream(file);
FileInputStream fis2 = new FileInputStream(file);
//将文件二进制流保存到数据库
ExcelData excelData = new ExcelData();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis2.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
byte[] barray = bos.toByteArray();
excelData.setId("excel-template-01");
excelData.setExcelData(barray);
excelData.setExcelName(file.getName());
excelDataMapper.updateByPrimaryKeyWithBLOBs(excelData);
bos.close();
fis2.close();
}
}
//工具:将ins输入流写入已命名文件file
private void getInputStream(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
ExcelData.java
public class ExcelData {
private String id;
private String excelName;
private byte[] excelData;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getExcelName() {
return excelName;
}
public void setExcelName(String excelName) {
this.excelName = excelName == null ? null : excelName.trim();
}
public byte[] getExcelData() {
return excelData;
}
public void setExcelData(byte[] excelData) {
this.excelData = excelData;
}
}
表结构
CREATE TABLE `excel_data` (
`id` varchar(32) NOT NULL,
`excel_data` mediumblob COMMENT '文件二进制流',
`excel_name` varchar(128) DEFAULT NULL COMMENT 'excel的文件名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
三、后端下载代码
@ResponseBody
@RequestMapping(value = "/exportExcel.do", method = RequestMethod.POST)
public void exportExcel2(@RequestParam("id") String id, HttpServletResponse response) {
ExcelData excelData = excelDataMapper.selectByPrimaryKey(id);
String excelName = excelData.getExcelName();
InputStream is = new ByteArrayInputStream(excelData.getExcelData());
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;" + "filename=" + new String(excelName.getBytes("UTF-8"), "ISO-8859-1"));
ServletOutputStream outputStream = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}