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

相关推荐
web打印社区4 小时前
网页静默打印热敏小票:从 HTML 到出纸的完整指南
前端·javascript·vue.js·electron·pdf·html
码事漫谈5 小时前
勿删
后端
IT_陈寒9 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
唐青枫10 小时前
别把 ArrayList 当成会自动管理内存的 List:Zig 动态数组从入门到实战
后端
鸿蒙开发10 小时前
我为 HarmonyOS 做了一个统一大模型 SDK:@hmkit/ai 正式开源
后端
猪是念来过倒10 小时前
Semaphore 与 RateLimiter:并发控制双雄详解
后端
掘金者阿豪10 小时前
异构数据同步最怕什么?不是同步慢,而是数据对不上
后端
程序员cxuan11 小时前
Claude 官方的学习教程,太强了。
人工智能·后端·程序员
老孙讲技术11 小时前
把工地遮挡和掉线接进项目部:setMessageCallback 订 alarm 与 deviceStatus
后端·物联网·音视频开发
老孙讲技术11 小时前
关店后有人进门,监控值班群却没响:用 setMessageCallback 订 human,再用 aiHuman 打开人形
后端·物联网·音视频开发