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

相关推荐
南半球与北海道#1 分钟前
el-table合并单元格
javascript·vue.js·elementui·表格合并
MonKingWD12 分钟前
MySQL事务篇-事务概念、并发事务问题、隔离级别
数据库·后端·mysql
华仔啊13 分钟前
别学23种了!Java项目中最常用的6个设计模式,附案例
java·后端·设计模式
bobz96519 分钟前
openstack nova ironic 架构图以及流程
后端
咕白m62520 分钟前
C# 实现 PDF 转图片 - 分辨率设置、图片格式选择
后端·c#
Java水解29 分钟前
深入理解 SQL 中的 COALESCE、NULLIF 和 IFNULL 函数
后端·sql
PetterHillWater36 分钟前
开源知识库项目WeKnora技术拆解
后端·aigc
啷咯哩咯啷40 分钟前
element-plus el-tree-v2大数据量勾选节点卡顿问题
前端·javascript·vue.js
用户21411832636021 小时前
dify案例分享-零代码搞定 DIFY 插件开发:小白也能上手的文生图插件实战
后端
石小石Orz2 小时前
效率提升一倍!谈谈我的高效开发工具链
前端·后端·trae