在springboot2.0以后文件上传的依赖spring已经自动帮我导入了,我们直接开整。
我们先创建上传后的路径
html页面:
<form action="/T_paper/addT_paper" id="info" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>论文题目:</td>
<td><input type="text" id="ti" name="title"></td>
<td id="te" style="color: red"></td>
</tr>
<tr>
<td>类型:</td>
<td><select name="t_type.typeCode">
<option th:each="t : ${type}" th:text="${t.typeName}"
th:value="${t.typeCode}"></option></td>
</tr>
<tr>
<td>论文摘要:</td>
<td><input type="text" id="paperSummary" name="paperSummary"></td>
<td id="te1" style="color: red"></td>
</tr>
<tr>
<td>论文内容:</td>
<td><input type="file" id="paperPath" name="filename"/></td>
<td id="te2" style="color: red">上传大小不能超过5M*上传文件类型必须为:doc docx</td>
</tr>
<tr>
<td><input type="submit" value="保存"> </td>
<td><input type="button" id="fh" value="返回"/></td>
</tr>
</table>
</form>
记得一定要加
如果需要进行对文件格式判和大小判断就要写jquery了
$("#info").submit(function() {
var title = $("#ti").val();
var paperSummary=$("#paperSummary").val();
var paperPath=$("#paperPath").val();//获取文件
var point = paperPath.lastIndexOf(".");
var type = paperPath.substr(point);//获取后缀
var fileSzie=$("#paperPath")[0].files[0].size;//获取文件大小,得到的值为字节类型
var judge=true;
if(title==""){
$("#te").html("论文标题不能为空")
judge= false;
}
if(paperSummary==""){
$("#te1").html("摘要不能为空")
judge=false;
}
if(paperPath==""||type!=".doc"||type!=".doc"||fileSzie>1000){
$("#te2").html("上传文件格式不正确")
judge=false;
}else{
$("#te2").html("")
}
return judge;
})
controller:
@RequestMapping("addT_paper")
public String addT_paper(T_paper t_paper,@RequestParam("filename")MultipartFile file){
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传路径
String filePath = "D:\\springboot\\PaperManage\\src\\main\\resources\\static\\FileUpload\\";
// 解决中文问题,liunx 下中文路径,图片显示问题
//fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
//上传
file.transferTo(dest);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
t_paper.setPaperPath(filePath+fileName);
service.addT_paper(t_paper);
return "redirect:pageInfo";
}