当前位置: 首页 > news >正文

springboot+vue上传图片

这里是一个简单的示例,演示了如何在Spring Boot中从Vue.js上传图像:

1.前端Vue.js代码:

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

http://www.lryc.cn/news/166207.html

相关文章:

  • 高压电缆护层接地环流及温度在线监测系统
  • 无涯教程-JavaScript - IPMT函数
  • 【EI会议征稿】第三届机械自动化与电子信息工程国际学术会议(MAEIE 2023)
  • 手写实现LRN局部响应归一化算子
  • 朗思科技数字员工通过统信桌面操作系统兼容性互认认证
  • 十六、Webpack常见的插件和模式
  • ChatGPT新增超强插件:文本直接生成视频、海报,支持自定义修改!
  • 亚像素边缘提取的例子
  • Wayland:推动Linux桌面进入下一代图形显示时代
  • mysql外键(foreign key)
  • 内网穿透——Windows搭建服务器
  • UE5.1 + Android 环境搭建
  • 华为python面试题目
  • IP代理安全吗?如何防止IP被限制访问?
  • 使用 gst-template 创建自己的 gstreamer 插件
  • nginx反向代理,用户访问服务器1的80端口,请求转发至服务器2,3的8882端口
  • Python学习笔记:导入txt、xlsx文件并做简单函数处理
  • uniapp 轮播列表左右滑动,滑动到中间放大
  • 5. 自动求导
  • 【IEEE会议】 第三届智能通信与计算国际学术会议(ICC 2023)
  • 巨人互动|Facebook海外户Facebook风控规则有什么
  • pip命令来查看当前激活的虚拟环境
  • STL stack 和 queue
  • 阈值回归模型(Threshold Regression Model)及R实现
  • 无人机通信协议MAVLink简介
  • 【办公自动化】用Python批量从上市公司年报中获取主要业务信息
  • 【sizeof()的使用方式】简洁明了初识C语言
  • 10. 正则表达式匹配
  • [Unity]GPU Instancing 无效的原因
  • 2023 年前端编程 NodeJs 包管理工具 npm 安装和使用详细介绍