本文描述场景为
上传:前端上传图片,后端存储到mysql数据库中;
多图片上传
先看一下后端数据表
import com.zpmc.common.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Blob;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ApiModel
@Entity
@Table(name = "tb_image")
public class Image extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "task_id")
private Integer taskId;
@Column(name = "directory", length = 200)
private String directory;
@Column(name = "file")
private Blob file;
@Column(name = "remark", length = 200)
private String remark;
@Column(name = "STATUS", length = 200)
private Integer status;
}
前端
multiple: 不用给参数,默认为true,多文件上传
show-file-list=“false”:不展示图片列表
accept=“.jpg,.png,.jpeg”:允许上传的文件格式
auto-upload=“true”:启动自动上传
:action=“imageUploadUrl” :后端上传图片接口地址
:headers=“uploadHeaders”:请求头
:on-success=“getImageList()”:上传成功后重新查询展示
<div class="uploadImage-left"><el-button> <el-upload accept=".jpg,.png,.jpeg" :show-file-list="false" multiple :auto-upload="true" :action="imageUploadUrl" :headers="uploadHeaders" :on-success="getImageList()">上传图片
</el-upload></el-button></div>
data() {
return {
imageUploadUrl: "自己的后端接口地址/image/importImage",
uploadHeaders: {
Authorization: Cookie.get("自己的token"),
},
};
},
后端
Controller层
@ApiOperation("导入图片")
@PostMapping("importImage")
public Result importImage(@RequestParam(value="file") MultipartFile[] files) throws Exception {
return imageService.importImage(files);
}
Service层
@Override
public Result importImage(MultipartFile[] files) throws SQLException {
Connection connection = null;
PreparedStatement ps = null;
InputStream ins=null;
try {
connection = new JDBCConnection().getConnection();
for (int i = 0; i < files.length; i++) {
//先创建,再修改
Image image = new Image();
ins = files[i].getInputStream();
image = imageRepo.save(image);
String sql = "update tb_image set file=? where id=?";
ps = connection.prepareStatement(sql);
ps.setBlob(1, ins);
ps.setInt(2, image.getId());
ps.execute();
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
ps.close();
}
return Result.success("上传成功");
}