(不建議使用,會影響項目的運行速度)
前言:
現在的web項目是都是有圖片的,而企業級的都有專門的存儲服務器,但是對於個人使用,我目前知道的就有兩種
第一種是文件數據不在數據庫,而是在項目中建立一個文件夾,文件的上傳和讀取都是在該文件夾下存取,只有文件名存儲到數據庫,這種有一個缺點,我的數據當吧生成的war包刪除以后就有無法找到上傳的文件數據了,需要重新上傳;
第二種是把圖片存儲到數據庫中,以二進制的方式存儲到數據庫,然后讀取的時候再讀取
我更偏向於第二種,具體的操作如下:
*我的是springboot項目:
數據庫的表:
javabean:
public class Image { private Integer id; private String imageName; private String imageUrl; private byte[] imageContent;
//get和set方法自己添加,這里只為說明要義 }
controller層:
@RequestMapping("/imageupload") @ResponseBody public Object searchMember(MultipartFile file){ try { InputStream ins = file.getInputStream(); byte[] buffer=new byte[1024]; int len=0; ByteArrayOutputStream bos=new ByteArrayOutputStream(); while((len=ins.read(buffer))!=-1){ bos.write(buffer,0,len); } bos.flush(); byte data[] = bos.toByteArray(); Image image =new Image(); image.setImageContent(data); image.setImageName("test"); image.setImageUrl("/testimage"); int result = imageService.insert(image); return "ok"+result; /* Student s=new Student(); s.setId(sId); s.setPhoto(data); studentService.insertPhoto(s);*/ } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return "ok"; } /** * 從數據庫到頁面顯示圖片 * @return */ @RequestMapping(value = "/showimage",produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] toImageShow(){
//這里是從數據庫讀取圖片,你可以根據自己的業務讀取你的數據 Image image =imageService.selectByPrimaryKey(1); return image.getImageContent(); }
上傳的頁面:
<form action="/imageupload" method="post" enctype ="multipart/form-data"> <label for="file" class="btn btn-primary" style="float: left;height: 30px;width: 180px;margin-right: 20px">點擊選擇考生照片</label> <input id="file" name="file" type="file" style="float: left;display:none"/> <input class="btn btn-primary" type="submit" value="提交" style="float: left"> </form>
顯示的頁面:
<img src="/showimage" alt="失敗" />
最后感謝一下以下博客:
https://blog.csdn.net/u014449560/article/details/82807517
https://www.cnblogs.com/xiaowangxiao/p/10936537.html