注:
自己记录留备用持续学习持续更新下面代码只适合和我一样的菜鸟查看,持续更新。
这个是直接图片存入数据并不是将图片存入服务器数据库存路径的,写法略有出入……
整体流程就是获得图片转换为流输出为byte[]存库
代码:
/**
* 保存图片
* @param reportId(这个不需要管)
* @param multipartFile
* @return
* @throws CcException
* @throws IOException
* MultipartFile[] 接收多个图片,一个图片直接MultipartFile接收
*/
@Override
public boolean pcuploadImg(Integer reportId, MultipartFile[] multipartFile) throws CcException, IOException {
if(null == reportId)
throw new CcException("请重新选择!");
if(multipartFile.length == 0 || null == multipartFile)
throw new CcException("请选择图片!");
LogReport img = surveyReportDao.findImgById(reportId);
if(img == null)
throw new CcException("请退出重新选择!");
InputStream inPut = null;
byte[] bus = null;
byte[] by = null;
try {
for (int i = 0; i < multipartFile.length; i++) { //不好意思这一步直接取消半成品代码
MultipartFile imgFile = multipartFile[i]; //一个图片不需要遍历直接放入流中
inPut = imgFile.getInputStream();
if(inPut != null)
by = new byte[inPut.available()]; //创建当前图片字节大小的byte
//在内存创建一个字节数组缓冲区
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int n;
//inPut.read(by)从(来源)输入流中(读取内容)读取的一定数量字节数,并将它们存储到(去处)缓冲区数组by中
while ((n = inPut.read(by)) != -1) {
bos.write(by, 0, n); //参数:1、要输出的字节数组 2、从什么位置开始 3、多少个字节 写入此字节数组输出流
}
bus = bos.toByteArray(); //创建一个新分配的字节数组。数组的大小和当前输出流的大小,内容是当前输出流的拷贝。
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
inPut.close();
}
LogReport log = new LogReport();
log.setRid(reportId);
log.setImg(bus);
return surveyReportDao.upDateImg(log);
}
下面取出代码:
@Override
public LogReport showloadImg(Integer reportId, HttpServletResponse response) throws CcException , IOException{
if(null == reportId)
throw new CcException("请选择!");
LogReport log = surveyReportDao.findImgById(reportId);
if(null == log.getImg())
throw new CcException("图片为空!");
OutputStream out = null;
try {
out = response.getOutputStream();
out.write(log.getImg());
} catch (Exception e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
return log;
}