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

相关推荐
满栀5852 分钟前
vue动态路由效果
前端·javascript·vue.js·前端框架·vue
65岁退休Coder28 分钟前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境39 分钟前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
码流怪侠40 分钟前
用 WiFi 信号数人头:howmanypeoplearearound 项目深度解析
后端·开源·github
心运软件1 小时前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
jjw_zyfx2 小时前
css vue vite实现闪烁的呼吸效果
javascript·css·vue.js
Jodie同志2 小时前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent
Jodie同志2 小时前
第1~15天:原生Agent、RAG与LangGraph基础(完整代码实操)
前端·后端·agent
Zane19942 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端
用户69371750013842 小时前
#DeepSeek+Pi‑Agent 王炸组合跑赢 Claude‑Code!
前端·人工智能·后端