我返回了图片的上传路径,前台也打印了确认传进去了,但是数据库表是空白的,什么都没有,请问是哪里的代码有问题呢?
<el-col :span="8">
<el-form-item label="物资图片" prop="unit">
<el-upload
accept="image/jpeg,image/png"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
ref="upload"
:action="'http://localhost:8989/api/uploadImage'"
:http-request="upload"
:auto-upload="false"
:before-upload="onBeforeUpload"
multiple
:limit="1"
:on-exceed="handleExceed"
v-model="addForm.pictures">
<el-button size="small" type="primary">点击上传el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过1M
el-upload>
el-form-item>
el-col>
el-row>
<el-form-item>
<el-button type="primary" @click="addIn">立即捐赠el-button>
el-form-item>
addIn() {
this.$refs.upload.submit();
this.$refs.addFormRef.validate(async valid => {
if (!valid) return;
const {data: res} = await this.$http.post("addIn2", this.addForm);
if (res != "success") {
return this.$message.error("捐赠失败~");
}
this.$message.success("捐赠成功~");
this.addDialogVisible = false;
});
},
<insert id="addIn">
INSERT INTO instock
(itemname,numbers,fromwho,worker,state,unit,pictures)
VALUE
(#{itemname},#{numbers},#{fromwho},#{worker},#{state},#{unit},#{pictures})
insert>
@RequestMapping(value = "/api/uploadImage", method = RequestMethod.POST)
@ResponseBody
public String uploadImage(@RequestParam("files") MultipartFile file) throws IOException {
System.out.println(file.getOriginalFilename() + "图片已传入!!");
byte[] b = file.getBytes();
String fileName = file.getOriginalFilename();
Path path = Paths.get("src/main/resources/pictures/" + fileName);
Files.write(path, b);
String receivePath = path.toString();
return receivePath;
}
首先需要确认一下代码中图片上传路径的相关逻辑是否正确,比如文件是否成功上传到了服务器指定的目录下。如果确认文件上传成功,那么需要检查一下数据库表的相关配置是否正确,包括表名、字段名、字段类型等等。另外,也需要确认一下代码中插入数据的逻辑是否正确,包括是否成功连接了数据库、是否正确执行了插入语句等等。以下是一个简单的Java代码示例,用于将图片上传路径插入到数据库表中:
// 假设图片上传路径为filePath,数据库表名为tableName,数据库字段名为columnName
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "username", "password");
// 创建SQL语句
String sql = "INSERT INTO " + tableName + " (" + columnName + ") VALUES (?)";
// 使用PreparedStatement预编译SQL语句
PreparedStatement pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setString(1, filePath);
// 执行SQL语句
pstmt.executeUpdate();
// 关闭PreparedStatement和数据库连接
pstmt.close();
conn.close();
需要注意的是,以上代码示例中的db_name、username和password需要根据实际情况进行替换。另外,为了避免SQL注入攻击,建议使用PreparedStatement来预编译SQL语句并设置参数。