一、效果展示
包括文件上传面板以及文件上传列表
二、介绍
长话短说,采用spring springMVC mybatis maven mysql,实现多文件上传功能,下载使用的是流的形式。
其中涉及的分页我会另开一片博客介绍。
三、准备材料
plupload
artDialog
还有一份初始化插件的js文件
这些可以直接从我的分享连接里面下载
链接:http://pan.baidu.com/s/1c27cTAK 密码:btqj
还有jquery 这个自行下载
四、前台代码
引入样式以及js文件
<link rel="stylesheet" href="resources/css/plupload.css" type="text/css"> <script src="resources/js/jquery.min.js"></script>
<script src="resources/upload/plupload.full.min.js"></script>
<script src="resources/artDialog4.1.7/artDialog.source.js?skin=blue"></script>
<script src="resources/js/upload.js"></script>
js代码
_plupload(绑定的uuid,文件上传路径);
①关于绑定的uuid,我举个例子,当前用户的id就是uuid,你可以把用户id和你上传的文件相关联,以后查询的话根据用户id就能查询这个用户上传的所有文件
②这个方法是封装过的,在upload.js里面能看到,我里面注释写的很清楚,也可以参考官方文档
$(function() {
$('#uploadBtn').click(function() {
popUpDialog();
});
_plupload('test','${pageContext.request.contextPath}/uploadfile'); });
页面代码,一个按钮,一个弹出框
<a id="uploadBtn" class="optionbtn inline" href="#">文件上传</a>
<!-- 触发弹出框 -->
<div id="uploadContent" style="display: none; height: 300px; overflow-x: hidden; overflow-y: auto;">
<div id="choosefile">
<span>单个文件支持小于100M</span><br /> <a id="uploadify" href="javascript:void(0);">选择文件</a>
</div>
<div id="uploadfileQueue" style="border: 1px solid #a7c5e2; height: 228px; width: 350px;"></div>
</div>
<pre id="console"></pre>
五、后台代码
我都没有封装成方法,为了看得明白,可以自己封装一下
/**
* 文件上传请求地址
*
* @param request
* @param response
*/
@RequestMapping("uploadfile")
public void upload(HttpServletRequest request, HttpServletResponse response) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;// 二进制上传
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");// 获取文件 String unid = UUID.randomUUID().toString().replace("-", "");/* 文件主键 */
String originalFilename = file.getOriginalFilename();/* 原文件名,包括后缀 */
String flieSize = String.valueOf(file.getSize());/* 文件大小 */
String path = null;/* 文件存储路径 */
String punid = request.getParameter("punid"); /* 关联文件punid */ // 保存文件
if (file != null) {
try {
String basePath = request.getSession().getServletContext().getRealPath("/uploadfile");
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
String subPath = sdf.format(new Date());
path = basePath + subPath + unid + File.separator + originalFilename; // 如果文件夹不存在,就创建文件夹
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
file.transferTo(dir);
} catch (Exception e) {
e.printStackTrace();
}
} // 文件大小转换
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
long size = Long.parseLong(flieSize);
if (size >= gb) {
flieSize = String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
flieSize = String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
flieSize = String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else {
flieSize = String.format("%d B", size);
} // 存储文件信息进数据库
FileUpload fileUpload = new FileUpload();
fileUpload.setUnid(unid);
fileUpload.setOriginalFilename(originalFilename);
fileUpload.setFlieSize(flieSize);
fileUpload.setPath(path);
fileUpload.setPunid(punid);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
fileUpload.setFlieTime(df.format(new Date()));
fileUploadService.insert(fileUpload);
}
这里附带一个下载的方法,是用文件流,根据文件id来进行下载
@RequestMapping("downloadfile")
public void downLoadfile(HttpServletRequest request, HttpServletResponse response) {
String unid = request.getParameter("unid");
FileUpload fileUpload = fileUploadService.selectByPrimaryKey(unid);
if (fileUpload != null) {
try {
String filename = new String(fileUpload.getOriginalFilename().getBytes("GBK"), "ISO-8859-1");
String path = fileUpload.getPath();
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
response.setHeader("Content-Length", fileUpload.getFlieSize()); InputStream inputStream = new FileInputStream(new
File(path));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
还有一个删除方法
/**
* 文件删除
*
* @param request
* @param response
*/
@ResponseBody
@RequestMapping("delfile")
public Map<String, Object> delfile(HttpServletRequest request, HttpServletResponse response) {
String unid = request.getParameter("unid");
FileUpload fileUpload = fileUploadService.selectByPrimaryKey(unid);
// 删除本地
boolean flag = false;
File file = new File(fileUpload.getPath());
if (file.exists()) {// 路径为文件且不为空则进行删除
flag = file.delete();
}
// 删除数据库
int result = fileUploadService.deleteByPrimaryKey(unid);
if (result > 0) {
flag = true;
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("result", flag);
return map;
}
六、最后
如果要完整的代码可以给我留言,我发给你