https://gitee.com/dafran/file_upload
Controller
@RestController
public class FileUploadController {
//时间格式化区分
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
Map<String, Object> result = new HashMap<>();
//文件原始名
String originName = file.getOriginalFilename();
//判断是否是pdf文件
if (!originName.endsWith(".pdf")) {
result.put("status","error");
result.put("msg","文件类型错误");
return result;
}
//日期
String format = sdf.format(new Date());
//保存文件文件夹。获取的是当前项目路径,可以写死
String realPath = req.getServletContext().getRealPath("/") + format;
File folader = new File(realPath);
//是否有文件夹,没有则创建
if (!folader.exists()) {
folader.mkdirs();
}
//新文件名
String newName = UUID.randomUUID().toString()+".pdf";
try {
file.transferTo(new File(folader,newName));
String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
result.put("status","success");
result.put("url",url);
} catch (IOException e) {
result.put("status","error");
result.put("msg",e.getMessage());
}
return result;
}
}
前端页面渲染
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-upload
action="/upload"
:on-preview="handlePreview"
accept=".pdf"
:limit="10">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
</el-upload>
</div>
<!--import Vue before Element-->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!--import JavaScript-->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
methods:{
handlePreview(file) {
window.open(file.response.url);
}
}
})
</script>
</body>
</html>