今天我們來看看SSM中如何將圖片轉換成二進制,最后傳入到自己的數據庫中,好了,廢話不多說,我們開始今天的學習,我這里用的編輯器是IDEA
1、導入圖片上傳需要的jar依賴包
1 <dependency> 2 <groupId>commons-io</groupId> 3 <artifactId>commons-io</artifactId> 4 <version>2.4</version> 5 </dependency> 6 7 <dependency> 8 <groupId>commons-io</groupId> 9 <artifactId>commons-io</artifactId> 10 <version>1.4</version> 11 </dependency> 12 13 <dependency> 14 <groupId>commons-fileupload</groupId> 15 <artifactId>commons-fileupload</artifactId> 16 <version>1.3.1</version> 17 </dependency>
2、通過form表單提交到Controller控制層中,但是需要注意一點,圖片上傳的請求方式必須是POST,否則會出現報錯
然后在當前的JSP頁面中的頭部加入以下代碼,防止出現中文亂碼
<meta http-equiv="Content-Type" content="multipart/form-data;charset=utf-8" />
3、在自己的form表單后面加入下面這行代碼,它的作用是將圖片轉換成二進制進行傳遞,但是它也有自身缺點,它會將你所有傳遞的信息都轉換成二進制
enctype="multipart/form-data"
4、一系列工作完事之后,我們來開始寫Controller控制層中的代碼,圖片上傳路徑切記要寫自己的上傳路徑,
pictureFile這個是我的圖片的傳遞名,這個一定要寫自己的圖片上傳名
<label class="layui-form-label">請選擇上傳圖片:<input type="file" name="pictureFile" class="layui-upload-file"></label>
@RequestMapping("這里寫form表單提交的請求路徑")
public String shengadd(HttpServletRequest request, Sheng sheng, MultipartFile pictureFile) throws Exception {
System.out.println("***");
//使用UUID給圖片重命名,並去掉四個“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
//獲取文件擴展名
String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
//設置圖片上傳路徑
String url = request.getSession().getServletContext().getRealPath("/statics/img");
System.out.println(url);//輸出文件名
//以絕對路徑保存重命名后的圖片
pictureFile.transferTo(new File(url + "/" + name + "." + ext));
//把圖片儲存路徑保存到數據庫
sheng.setImg("statics/img/" + name + "." + ext);
userService.riyongadd(sheng);
return "redirect:/redutime.html";
}
5、最后一項,在springmvc-servlet.xml文件中插入文件上傳解析器
<!-- 定義文件上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設定默認編碼 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 設定文件上傳的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
好了,我們開始來測試代碼結果:可以看到圖片已經上傳到自己所需要的路徑里面,也保存到了數據庫中

