1. 前端组件:
<input type="file" name="fileName3" id="fileName3">
<input type="button" class="btn btn-secondary" onclick="sendToEnd()">上传论文</input>
2. 脚本:
function sendToEnd(){
alert("tset");
var $file1 = $("input[name='fileName3']").val();
if ($file1 == "") {
alert("请选择上传的目标文件! ")
return false;
}
var size1 = $("input[name='fileName3']")[0].files[0].size;
if (size1>104857600) {
alert("上传文件不能大于100M!");
return false;
}
boo1 = true;
var type = "file";
var formData = new FormData();
formData.append(type,$("#fileName3")[0].files[0]);
$.ajax({
type : "post",
url : "/clazz/upload/end",
data : formData,
processData : false,
contentType : false,
success : function(data){
if (data) {
alert("文件上传成功!");
}else{
alert("文件上传失败!");
}}
});
}
3. 控制器
@RequestMapping("/upload/end")
@ResponseBody
public Boolean uploadEnd(@RequestParam("file") MultipartFile file, HttpServletRequest req)
throws IllegalStateException, IOException {
if (file.isEmpty()) {
return false;
}
String path = req.getServletContext().getRealPath("/WEB-INF/");
HttpSession session = req.getSession();
Student student = (Student)session.getAttribute("user");
path+="/后期/";
path += student.getSnumber();
String fileName = file.getOriginalFilename();
File filePath = new File(path, fileName);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
System.out.println("创建目录" + filePath);
}
file.transferTo(filePath);
String[] split = filePath.toString().split("WEB-INF");
System.out.println("url:"+split[1]);
student.setEndUrl(split[1]);
Example example = new Example(Student.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("id", new Long(student.getId()));
example.and(criteria);
int flag = studentMapper.updateByExampleSelective(student,example);
return true;
}
4. 在springmvc.xml配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="17367648787"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>