springboot+vue上传图片

这里是一个简单的示例,演示了如何在Spring Boot中从Vue.js上传图像:

1.前端Vue.js代码:

html 复制代码
<template>
  <div>
    <input type="file" @change="handleFileUpload">
    <button @click="uploadImage">上传图片</button>
  </div>
</template>

<script>
export default {
  name: 'ImageUploader',
  data() {
    return {
      imageFile: null,
      imageUrl: ''
    };
  },
  methods: {
    handleFileUpload(event) {
      this.imageFile = event.target.files[0];
    },
    uploadImage() {
      let formData = new FormData();
      formData.append('image', this.imageFile);
      axios.post('/api/image/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        this.imageUrl = response.data.imageUrl;
      });
    }
  }
};
</script>
  1. 后端Spring Boot代码:
java 复制代码
@RestController
public class ImageController {

    @Value("${upload.path}")
    private String uploadPath;

    @PostMapping("/api/image/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                Path filePath = Paths.get(uploadPath + "/" + fileName);
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                String imageUrl = "/api/image/" + fileName;
                response.put("imageUrl", imageUrl);
            } else {
                response.put("status", "error");
                response.put("message", "No file uploaded");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (IOException e) {
            response.put("status", "error");
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
        response.put("status", "success");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/api/image/{fileName:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String fileName) throws IOException {
        Path filePath = Paths.get(uploadPath + "/" + fileName);
        Resource resource = new UrlResource(filePath.toUri());
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(resource);
    }
}

这是一个非常简单的示例,涵盖了从Vue.js前端上传一个图像并将其保存到Spring Boot后端服务器的全部过程。你可以根据实际需求进行修改和扩展。

相关推荐
程序员老乔20 分钟前
Java 新纪元 — JDK 25 + Spring Boot 4 全栈实战(三):虚拟线程2.0,电商秒杀场景下的并发革命
java·开发语言·spring boot
椰子皮啊1 小时前
mediasoup+Vue3避坑指南:解决黑屏、闪屏、流绑定失效三大难题
vue.js·前端框架
江沉晚呤时1 小时前
.NET 9 快速上手 RabbitMQ 直连交换机:高效消息传递实战指南
开发语言·分布式·后端·rabbitmq·.net·ruby
编码忘我1 小时前
java单机滑动窗口限流器
后端
编码忘我1 小时前
redis的数据类型及java调用案例
后端
编码忘我1 小时前
redis分布式锁
后端
程序员爱钓鱼2 小时前
Go输出与格式化核心库:fmt包完整指南
后端·面试·go
于慨2 小时前
spring boot
java·数据库·spring boot
lars_lhuan2 小时前
Go map 与并发
后端·golang
吠品2 小时前
Vue项目Moment.js引入优化:全局挂载与按需引入的深度解析与最佳实践
前端·javascript·vue.js