今天写到了上传文件部分,记录一下。
前端使用了dropzone.js(用于实现文件上传的JS库),并对此文件进行了细微修改。
说一下思路吧:
首先界面长这样:

点击上传文件,需要弹出一个对话框,对话框中有支持拖拽文件的文件选择框。

注意,此时上传按钮是禁用的。
选择完成后,会有上传进度条。这里为了看到进度条,我选择上传一个比较大的文件。

进度条走满之后才可以点击上传按钮。点击上传刷新界面:


可以看到上传成功了。
接下来说一下实现吧:
一、dropzone的文件上传表单
<div class="modal fade" id="upload-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title">选择您需要上传的文件,可以拖拽</h4>
</div>
<div class="modal-body">
<form action="<%=basePath%>/doc/uploadfile.do?"
id="uploadfileform" class="dropzone"
enctype="multipart/form-data">
<!-- <input type="file" name="file" id="btn_file" multiple> -->
</form>
<!--style="display: none" -->
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> -->
<button type="button" class="btn btn-default" onclick="closeUploadFileDialog()"> 关闭</button>
<button type="button" class="btn btn-default disabled" id ="submitbutton">上传</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
核心就是引入dropzone.js后。添加一个表单标签,设置class="dropzone"。然后dropzone会自动检测到,并做大量的工作。
这里我修改了一下dropzone.js的几行代码。来满足我的需求。
主要是processing和success两个事件。processing表示正在上传的事件,success表示上传成功。可以看到这里当在上传的时候,我让按钮变成不能点击的状态。上传成功后,根据服务器返回的消息Message,把按钮变回可点击状态,然后添加点击函数,让界面重新加载。


二、SpringMVC后台实现
有些请求参数是我业务需求,不用在意,主要是看获得文件保存路径,和file.transferTo(newFile);
在controller中使用MultipartFile file
来接受前端传过来的文件,使用file对象可以获得这个文件的一些属性,比如文件名,文件大小等等。
@RequestMapping(value = "uploadfile.do", method = RequestMethod.POST)
@ResponseBody
public Map<String, Integer> uploadfile(HttpServletRequest request, @RequestParam("parentID") String parentID,
@RequestParam("file") MultipartFile file, @RequestParam("team_id") String teamID) {
String folderName = teamID;
String filePath = FileStorage.getFileRealPath() + folderName;
File parentPath = new File(filePath);
if (!parentPath.exists()) {
parentPath.mkdirs();
}
String realpath = parentPath + "\\" + file.getOriginalFilename();
Long filesize = file.getSize();
String fileOwner = ((User) request.getSession().getAttribute("user")).getUsername();
Date now = new Date();
File newFile = new File(realpath);
try {
file.transferTo(newFile);
int uploadFiles = fileService.uploadFiles(file.getOriginalFilename(), fileOwner, filesize, now, 1, teamID,
realpath, parentID);
System.out.println(uploadFiles);
Map<String, Integer> resultmap = new HashMap<String, Integer>();
resultmap.put("msg", uploadFiles);
return resultmap;
} catch (Exception e) {
e.printStackTrace();
Map<String, Integer> resultmap = new HashMap<String, Integer>();
resultmap.put("msg", 0);
return resultmap;
}
}
三、数据库
至于数据库的部分,有两点需要做:
①:在文件实体表插入文件的信息
②:在文件关系表中插入此文件与父文件的关系。
这个我在Service层实现的,就不贴出来了。知道要做这两件事就行。
网友评论