多图片上传存储到数据库(vue+springboot+elementUI)
在Vue.js前端,使用Element UI的<el-upload>
组件来上传图片,然后将图片转换为Base64字符串发送到后端。后端使用Spring Boot接收Base64字符串,并将其存储到数据库中。
前端代码(Vue + Element UI):
<template>
<el-upload
action="#"
list-type="picture-card"
:on-change="handleChange"
:on-remove="handleRemove"
:file-list="fileList"
multiple>
<i class="el-icon-plus"></i>
</el-upload>
<el-button @click="uploadImages">上传图片</el-button>
</template>
<script>
export default {
data() {
return {
fileList: [],
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList;
},
handleRemove(file, fileList) {
this.fileList = fileList;
},
uploadImages() {
const images = this.fileList.map(file => {
return this.getBase64(file.raw);
});
Promise.all(images).then(base64Images => {
// 发送base64Images到后端
axios.post('/upload', { images: base64Images }).then(response => {
console.log(response.data);
});
});
},
getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result);
reader.onerror = e => reject(e);
reader.readAsDataURL(file);
});
},
},
};
</script>
后端代码(Spring Boot):
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
@RestController
public class ImageUploadController {
private final JdbcTemplate jdbcTemplate;
public ImageUploadController(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@PostMapping("/upload")
public ResponseEntity<?> uploadImages(@RequestBody List<String> images) {
// 存储Base64字符串到数据库
for (String image : images) {
String sql = "INSERT INTO images (image) VALUES (?)";
jdbcTemplate.update(sql, image);
}
return ResponseEntity.ok("Images uploaded successfull
评论已关闭