最近在完成自己的毕业设计,但文件的上传功能以前都没有遇到过,花了两天的时间解决了。期间遇到了较多的问题,现对该功能做记录。
- 前端(使用BootStrap和ajax)
- 后端使用Spring、Spring MVC和Mybatis
- 这里主要包含两个功能:(1)使用下拉列表选择上传者,其中的信息通过ajax获取并动态添加;(2) 创建上传文件的按钮,并通过点击上传按钮 实现文件的上传
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form id="uploadfile" role="form" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="uploader">上传者</label> <select id="uploader" name="uploader"></select>
</div>
<div class="form-group">
<label for="uploadFile">文件上传</label><input type="file"
id="file" name="file" />
<p class="help-block">这里显示帮助文档</p>
</div>
<button type="button" class="btn btn-default" onClick="commit()">上传</button>
</form>
</div>
</div>
</div>
//获取所有的上传者信息,并动态添加到`select`选择框中
$(document).ready(
function() {
$.ajax({
type : "POST",
url : "${ctx}/employeeControl/getallEmoloyee",
success : function(data) {
$("#uploader").append(
'<option value=0>请选择</option>');
for (var i = 0; i < data.length; i++) {
$("#uploader").append(
'<option value="'+data[i].employee_id+'">'
+ data[i].username
+ '</option>');
}
}
});
});
//重点是这里
function commit() {
var uploader = $("#uploader").val();//获得`select`选择器的value值
var file = $("#file")[0].files[0];//获得上传文件
var form = new FormData();//初始化formDate对象
//将两个变量通过append方法添加到formdata中,append方法中的第一个参数必须与后端请求的一致,第二个参数就是我们获取到的值
form.append("uploader",uploader);
form.append("file",file);
$.ajax({
type : "POST",
//文件的上传路径
url : "${ctx}/fileControl/addFile",
//将formdata对象添加为参数
data : form,
//开启异步
async : true,
cache : false,
contentType : false,
processData : false,
success : function(data) {
//后端返回"SUCCESS"或"ERROR"
alert(data)
}
});
}
- 后端控制层代码
@RequestMapping(value = "/addFile")
@ResponseBody
public String addFile(@RequestParam("file") CommonsMultipartFile uploadFile, HttpServletRequest request,
@RequestParam(value="uploader") Integer uploader) {
log.info("文件:"+uploadFile+"uploader:"+uploader);
com.example.oa.domain.File f = new com.example.oa.domain.File();
String filename = uploadFile.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("uploadfile");
if (request instanceof MultipartHttpServletRequest) {
String filepath = path + File.separator + filename;
f.setFile_location(filepath);
f.setFilename(filename);
f.setFilesize(uploadFile.getSize());
f.setEmployee_id(uploader);
log.info("文件路径:" + path);
log.info("名字" + uploadFile.getOriginalFilename());
log.info(uploadFile.getSize());
File file = new File(path, filename);
if (!file.exists()) {
file.mkdirs();
}
try {
uploadFile.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
return "ERROR";
} catch (IOException e) {
e.printStackTrace();
return "ERROR";
}
boolean isadded = fileservice.addFile(f);
if (isadded) {
return "SUCCESS";
}
return "ERROR";
}
return "ERROR";
}
}
后端没什么好说的,获得前端传过来的参数,创建文件夹,并使用set方法将文件信息返回给服务层,再讲信息添加到数据库即可。
我的毕业设计托管在码云上,该功能也包含其中,如果遇到问题,希望能帮助到你
https://gitee.com/longhaicheng/OA_system
至此,使用ajax实现文件的上传就完成了