1.java的ssm框架后端,前段vue如何将图片上传到mysql存储起来。
2.将图片数据从mysql中提取出来返回前端并展示出来
java的ssm+vue图片存储到mysql并提取出来前端展示
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
5条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
要实现SSM(Spring + Spring MVC + MyBatis)框架与Vue.js前端之间的图片上传至MySQL数据库,并在前端展示,你需要遵循以下步骤:
- 首先,创建一个用于存储图片的Java实体类(Entity)。例如,名为
ImageInfo
的类,包含图片的元信息(如ID、名称、描述等),以及一个表示二进制图像数据的字段,如byte[] imageBytes
。
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class ImageInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; private byte[] imageBytes; // Getters and setters }
- 创建MyBatis映射文件(Mapper),用于执行CRUD操作。例如,
ImageInfoMapper.xml
:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.ImageInfoMapper"> <insert id="saveImage"> INSERT INTO image_info (name, description, image_bytes) VALUES (#{name}, #{description}, #{imageBytes}) </insert> <select id="getImageById" resultType="ImageInfo"> SELECT * FROM image_info WHERE id = #{id} </select> </mapper>
- 在Spring配置文件中注册MyBatis的相关配置,包括SqlSessionFactoryBean和MapperScannerConfigurer。
- 编写一个Spring MVC Controller来处理图片上传请求。首先,添加必要的依赖,如Spring WebMVC和Spring Commons FileUpload。然后,在Controller中创建一个方法处理POST请求,接收上传的文件。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.IOException; import java.util.List; @Controller @RequestMapping("/api/images") public class ImageController { @Autowired private ImageInfoService imageInfoService; @PostMapping("/upload") public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException { if (!file.isEmpty()) { ImageInfo imageInfo = new ImageInfo(); imageInfo.setName(file.getOriginalFilename()); imageInfo.setDescription("Uploaded by user"); imageInfo.setImageBytes(file.getBytes()); imageInfoService.saveImage(imageInfo); return ResponseEntity.ok("Image uploaded successfully."); } else { return ResponseEntity.badRequest().body("Please select a file to upload."); } } }
- 创建一个Spring Service类来调用Mapper的方法,进行业务逻辑处理。例如,
ImageInfoService.java
:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ImageInfoService { @Autowired private ImageInfoMapper imageInfoMapper; public void saveImage(ImageInfo imageInfo) { imageInfoMapper.saveImage(imageInfo); } public ImageInfo getImageById(Long id) { return imageInfoMapper.getImageById(id); } }
- 前端使用Vue.js构建表单,使用axios发送POST请求上传图片。这里我们使用一个简单的HTML模板和Vue实例作为示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Upload</title> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <form @submit.prevent="uploadImage"> <input type="file" ref="fileInput" accept="image/*" /> <button type="submit">Upload</button> </form> <img :src="imageUrl" v-if="imageUrl" alt="Uploaded Image" /> </div> <script> const app = new Vue({ el: '#app', data: { imageUrl: '' }, methods: { async uploadImage() { const file = this.$refs.fileInput.files[0]; if (file) { try { const formData = new FormData(); formData.append('file', file); const response = await axios.post('/api/images/upload', formData, { headers: {'Content-Type': 'multipart/form-data'} }); if (response.data === 'Image uploaded successfully.') { const imageInfo = await axios.get(`/api/images/${response.data}`); this.imageUrl = URL.createObjectURL(new Blob([imageInfo.data.imageBytes], {type: 'image/jpeg'})); } else { alert(response.data); } } catch (error) { console.error(error); alert('Failed to upload the image.'); } } else { alert('Please select an image to upload.'); } } } }); </script> </body> </html>
这样,用户就可以通过Vue表单选择图片并上传到服务器。图片会被存储到MySQL数据库中,前端会获取图片的ID,并根据这个ID从数据库中检索图片数据,然后将其转换为Blob对象并显示在页面上。注意,这里的图片格式是JPEG,如果你需要其他格式,可以相应地调整
URL.createObjectURL
中的类型参数。解决 无用评论 打赏 举报 编辑记录- 首先,创建一个用于存储图片的Java实体类(Entity)。例如,名为
悬赏问题
- ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
- ¥20 网站后台使用极速模式非常的卡
- ¥20 Keil uVision5创建project没反应
- ¥15 mmseqs内存报错
- ¥15 vika文档如何与obsidian同步
- ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
- ¥15 陆空双模式无人机飞控设置
- ¥15 sentaurus lithography
- ¥100 求抖音ck号 或者提ck教程
- ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)