今天写了上传文件,遇见了一些小小的问题,把完成版记录下来,做个记录
1、html+js(bootstarp)
此处用的是bootstarp框架
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">关闭</span>
</button>
<h3 class="modal-title" style="text-align: -webkit-left;">
添加附件
</h3>
</div>
<div class="modal-body">
<form id="fjform" name="jcsxform" class="form-horizontal" method="post">
<div class="form-group">
<label class="col-sm-3 control-label"> 附件上传</label>
<div class="col-sm-9">
<input type="file" name="myfile" data-ref="url2" multiple class="myfile file-loading"/>
<input type="hidden" name="url2" value="">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">
<i class="fa fa-close" aria-hidden="true"></i> 关闭
</button>
</div>
</div>
</div>
</div>
//设置文件上传对话框
$(".myfile").fileinput({
//上传的地址
uploadUrl: "<%=basePath%>filesUploads/fileUpd?MASTER_ID=" + recid,
uploadAsync: true, //默认异步上传
showUpload: true, //是否显示上传按钮,跟随文本框的那个
showRemove: false, //显示移除按钮,跟随文本框的那个
showCaption: true,//是否显示标题,就是那个文本框
showPreview: true, //是否显示预览,不写默认为true
dropZoneEnabled: false,//是否显示拖拽区域,默认不写为true,但是会占用很大区域
maxFilesNum: 1,
maxFileSize: 5000,
enctype: 'multipart/form-data',
validateInitialCount: true,
enctype: 'multipart/form-data',
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
allowedFileExtensions: ['jpg', 'gif', 'png', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'txt'],
previewFileIconSettings: {
'docx': '<i class="glyphicon glyphicon-file"></i>',
'xlsx': '<i class="glyphicon glyphicon-file"></i>',
'pptx': '<i class="glyphicon glyphicon-file"></i>',
'jpg': '<i class="glyphicon glyphicon-picture"></i>',
'png': '<i class="glyphicon glyphicon-picture"></i>',
'gif': '<i class="glyphicon glyphicon-picture"></i>',
'pdf': '<i class="glyphicon glyphicon-file"></i>',
},
language: 'zh'
}).on('filepreupload', function (event, data, previewId, index) {
}).on('fileuploaded', function (event, data, previewId, index) {//文件上传成功后
console.log(data);
parent.layer.msg('附件上传成功');
$("#myModal").modal('hide');
$("#uploadQueryTable").bootstrapTable('refresh');
});
2、java服务端
@ResponseBody
@RequestMapping(value = "/fileUpd")
public Object fileUpd(HttpServletRequest request) throws Exception {
List list = new ArrayList();
try {
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
User user = (User) session.getAttribute(Const.SESSION_USER);
String MASTER_ID = request.getParameter("MASTER_ID") + "";
String yyydd = DateUtil.getMonth();
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
//取得上传文件
List<MultipartFile> files = multiRequest.getFiles(iter.next());
if (files != null && files.size() > 0) {
for (MultipartFile multipartFile : files) {
//取得当前上传文件的文件名称
String fileName = multipartFile.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (fileName.trim() != "") {
String id = UuidUtil.get32UUID();
//重命名上传后的文件名
//String filename = fileName.substring(0,fileName.lastIndexOf("."));
String fileType = fileName.substring(fileName.lastIndexOf("."));
String newFileName = id + fileType;
String path = File.separator + yyydd + File.separator + newFileName;
//硬盘路径是否存在,如果不存在则创建
String dstPath = BASE_PATH + File.separator + yyydd;
File dstFile = new File(dstPath);
if (!dstFile.exists()) {
dstFile.mkdirs();
}
//定义上传路径
String filePath = BASE_PATH + path;
File localFile = new File(filePath);
multipartFile.transferTo(localFile);
//保存数据库
PageData pd = this.getPageData();
pd.put("ID", id);
pd.put("FILE_NAME", fileName);
pd.put("BASE_PATH", BASE_PATH);
pd.put("PATH", path);
pd.put("FILE_SIZE", multipartFile.getSize());
pd.put("FILE_TYPE", multipartFile.getContentType());
pd.put("MASTER_ID", MASTER_ID);
pd.put("STATUS", "0");
pd.put("CREATE_ID", user.getUSER_ID());
pd.put("CREATE_TIME", new Date());
filesUploadsService.save(pd);
Map map = new HashMap();
map.put("id", id);
list.add(map);
}
}
}
}
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
3、下载文件
@RequestMapping(value = "download")
public Object download(Model model, HttpServletRequest request, HttpServletResponse response) {
PageData pd = this.getPageData();
try {
//得到数据信息
PageData filesUploadsData = filesUploadsService.get(pd);
if (filesUploadsData == null) {
return null;
}
//得到文件名字
String fileName = filesUploadsData.getString("FILE_NAME") + "";
if (StringUtils.isNotBlank(fileName)) {
//设置请求头
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
//得到请求路径
String path = filesUploadsData.getString("BASE_PATH") + filesUploadsData.getString("PATH");
//用文件路径得到字节输入流
InputStream inputStream = new FileInputStream(new File(path));
//通过浏览器输出
OutputStream os = response.getOutputStream();
//定义一个用来缓冲的数组 就是每次读到的字节先放到缓存区然后一并输出提高效率;
byte[] b = new byte[2048];
//用来接收每次读到的字节数量;
int length;
//read(byte[]) 读取一定数量的字节也就是参数设置的大小 放到缓存区 返回每次读取的字节数量 read() 返回每次读取到的字节;
while ((length = inputStream.read(b)) > 0) {
//将缓存区的字节输出到目标文件 因为文件末尾读到的字节数不确定所以 每次输出缓存区的 0 到 实际读到的字节长度;
os.write(b, 0, length);
}
//因为输入出流用到系统级资源 所以要关流释放资源;
os.close();
inputStream.close();
}
//filesUploadsData.g
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}