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后端服务器的全部过程。你可以根据实际需求进行修改和扩展。

相关推荐
Loo国昌1 分钟前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
前端白袍25 分钟前
Vue:如何实现一个具有复制功能的文字按钮?
前端·javascript·vue.js
全靠bug跑29 分钟前
Spring Cloud OpenFeign 实战三部曲:快速集成 · 连接池优化 · 客户端抽取
java·spring boot·openfeign
new code Boy1 小时前
escape谨慎使用
前端·javascript·vue.js
北城以北88881 小时前
Spring定时任务与Spring MVC拦截器
spring boot·spring·mvc
Victor3561 小时前
Netty(20)如何实现基于Netty的WebSocket服务器?
后端
缘不易1 小时前
Springboot 整合JustAuth实现gitee授权登录
spring boot·后端·gitee
Kiri霧1 小时前
Range循环和切片
前端·后端·学习·golang
WizLC2 小时前
【Java】各种IO流知识详解
java·开发语言·后端·spring·intellij idea
Mr.朱鹏2 小时前
SQL深度分页问题案例实战
java·数据库·spring boot·sql·spring·spring cloud·kafka