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

相关推荐
geovindu32 分钟前
python:Lasso
开发语言·后端·python·算法
Csvn1 小时前
Nginx HTTPS 与安全加固:会话复用、OCSP、mTLS 与限流取舍
后端·nginx
码云社区1 小时前
Spring Boot上门按摩服务系统源码:上门到店服务目录与门店协同方案
java·spring boot·后端·上门服务·上门按摩·上门小程序
AAA修煤气灶刘哥1 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
Cosolar1 小时前
LoopForge:把团队的交付经验变成可执行的工程资产
人工智能·后端·agent
tong_li1 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(四):向量库搬进 Qdrant(向量数据库入门)
后端
Rain的Java大神之路2 小时前
大表 JOIN 不必靠堆内存:Dojao 的跨源 SQL、减量溢写与 Python UDF 实战
java·大数据·后端
她的男孩2 小时前
会签选了两个人,待办却生成一条谁也办不了:Forge Admin 按人拆开自选审批人
spring boot·低代码·工作流引擎
AAA修煤气灶刘哥2 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
Cosolar2 小时前
概率性计算的系统工程:从 Super-agent 与 Octop 看多 Agent 架构的收敛
人工智能·后端·架构