当前位置:   article > 正文

SpringBoot+Vue实现文件上传功能_vue+springboot实现文件上传

vue+springboot实现文件上传

目录

1.后端代码部分:

2.前端代码部分

3.效果展示

1.后端代码部分:

  1. @RestController
  2. @RequestMapping("/file")
  3. public class FileController {
  4. private final String UPLOAD_PATH = "D:/OBS/";//这里写上你需要上传的路径(模拟服务器)
  5. @PostMapping("/upload")
  6. public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) {
  7. // ... File upload logic ...
  8. if (file.isEmpty()) {
  9. return new ResponseEntity<>("文件不能为空", HttpStatus.BAD_REQUEST);
  10. }
  11. try {
  12. byte[] bytes = file.getBytes();
  13. Path path = Paths.get(UPLOAD_PATH + File.separator + file.getOriginalFilename());
  14. Files.write(path, bytes);
  15. return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
  19. }
  20. }
  21. }

2.前端代码部分

  1. <template>
  2. <div>
  3. <el-upload
  4. drag
  5. action="http://localhost:8081/file/upload"
  6. :on-success="handleUploadSuccess"
  7. :on-error="handleUploadError"
  8. >
  9. <i class="el-icon-upload"></i>
  10. <div class="el-upload__text">拖拽文件到此处上传</div>
  11. </el-upload>
  12. </div>
  13. </template>
  14. <script>
  15. export default {
  16. methods: {
  17. handleUploadSuccess(response, file) {
  18. this.$message.success('文件上传成功');
  19. },
  20. handleUploadError(err, file) {
  21. this.$message.error('文件上传失败');
  22. }
  23. }
  24. };
  25. </script>

3.效果展示

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/283691
推荐阅读
相关标签
  

闽ICP备14008679号