https://gitee.com/dafran/file_upload

    Controller

    1. @RestController
    2. public class FileUploadController {
    3. //时间格式化区分
    4. SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    5. @PostMapping("/upload")
    6. public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
    7. Map<String, Object> result = new HashMap<>();
    8. //文件原始名
    9. String originName = file.getOriginalFilename();
    10. //判断是否是pdf文件
    11. if (!originName.endsWith(".pdf")) {
    12. result.put("status","error");
    13. result.put("msg","文件类型错误");
    14. return result;
    15. }
    16. //日期
    17. String format = sdf.format(new Date());
    18. //保存文件文件夹。获取的是当前项目路径,可以写死
    19. String realPath = req.getServletContext().getRealPath("/") + format;
    20. File folader = new File(realPath);
    21. //是否有文件夹,没有则创建
    22. if (!folader.exists()) {
    23. folader.mkdirs();
    24. }
    25. //新文件名
    26. String newName = UUID.randomUUID().toString()+".pdf";
    27. try {
    28. file.transferTo(new File(folader,newName));
    29. String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
    30. result.put("status","success");
    31. result.put("url",url);
    32. } catch (IOException e) {
    33. result.put("status","error");
    34. result.put("msg",e.getMessage());
    35. }
    36. return result;
    37. }
    38. }

    前端页面渲染

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Title</title>
    6. <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    7. </head>
    8. <body>
    9. <div id="app">
    10. <el-upload
    11. action="/upload"
    12. :on-preview="handlePreview"
    13. accept=".pdf"
    14. :limit="10">
    15. <el-button size="small" type="primary">点击上传</el-button>
    16. <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
    17. </el-upload>
    18. </div>
    19. <!--import Vue before Element-->
    20. <script src="https://unpkg.com/vue/dist/vue.js"></script>
    21. <!--import JavaScript-->
    22. <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    23. <script>
    24. new Vue({
    25. el: '#app',
    26. methods:{
    27. handlePreview(file) {
    28. window.open(file.response.url);
    29. }
    30. }
    31. })
    32. </script>
    33. </body>
    34. </html>