背景描述:最近做到一個項目,有個商品登記功能。登記的信息包括:基本信息若干(文字信息);圖片信息,要求將圖片保存到數據表中的image字段(sql server 數據庫)
步驟:1.將圖片上傳到服務器的一個磁盤目錄下。
2.將剛才上傳好的圖片寫入數據庫image字段。
一、上傳圖片:使用的是spring mvc 對上傳的支持。
jsp 頁面:
<form name="uploadForm" id="uploadForm" method="post" action="${base}goods/doUploadFile" enctype="multipart/form-data"> <input type="file" name="image" /><br/> <input type="submit" value="上傳" class="btn4" /> </form>
spring_mvc.xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>
Controller:
@RequestMapping("/doUploadFile")
public ModelAndView doUploadFile(HttpServletRequest request,
HttpServletResponse response, HttpSession session)
throws Exception, IOException {
// 轉型為MultipartHttpRequest:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 獲得文件:
MultipartFile file = multipartRequest.getFile("image");
// 獲得文件名:
String filename = file.getOriginalFilename();
InputStream input = file.getInputStream();
// String path = "D:/goodsImages";下邊這個path是寫在配置文件里邊的,方便修改,這個方法很長但或得的結果就是路勁D:/goodsImages
String path = ConfigConstants.getInstance()
.get("goods.uploadImage.dir");
File savePath = new File(path);
if (!savePath.exists()) { // 文件夾
savePath.mkdir();
}
SaveFileFromInputStream(input, savePath.toString(), filename);
String result = "上傳成功!";
ModelAndView modelAndView = new ModelAndView("goods/uploadSuccess");
modelAndView.addObject("result", result);
modelAndView.addObject("filename", filename);
return modelAndView;
}
如此上傳就搞定了。
上傳文件補充,另一個方法:
1.項目中導入 jar 包 cos.jar
2.表單: enctype="multipart/form-data"
3.處理方法:主要用到 MultipartRequest 類 ,詳細情況查看:http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html
@RequestMapping(value = "/uploadImage.do") public String uploadImage(HttpServletRequest request) throws Exception { MultipartRequest mr = null; int maxPostSize = 1 * 100 * 1024; mr=new MultipartRequest(request,"E:\\goodsImages",maxPostSize,"GBK"); return null; }
二、生成略縮圖。
public void createIcon() { try { File fiBig = new File("D:/log/tickit.png"); // 大圖文件 File foSmall = new File("D:/log/tickitIcon.png"); // 將要轉換出的小圖文件 AffineTransform transform = new AffineTransform(); //讀取圖片 BufferedImage bis = ImageIO.read(fiBig); //獲得圖片原來的高寬 int w = bis.getWidth(); int h = bis.getHeight(); double scale = (double) w / h; //等比例縮放 int nowWidth = 120; int nowHeight = (nowWidth * h) / w; if (nowHeight > 120) { nowHeight = 120; nowWidth = (nowHeight * w) / h; } double sx = (double) nowWidth / w; double sy = (double) nowHeight / h; transform.setToScale(sx, sy); AffineTransformOp ato = new AffineTransformOp(transform, null); BufferedImage bid = new BufferedImage(nowWidth, nowHeight, BufferedImage.TYPE_3BYTE_BGR); ato.filter(bis, bid); ImageIO.write(bid, "png", foSmall); } catch (Exception e) { e.printStackTrace(); } }
三、圖片寫入數據庫。
1.圖片實體類的 圖片字段(picture) 用 byte[]類型
@Entity @Table(name = "spaq_pic") public class GoodsPic { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "pic_id") private Long picId; @Column(name = "pic_name") private String picName; @Column(name = "pic_descr") private String picDescr; @Column(name = "picture") private byte[] picture;// //省略其他字段及get,set方法 }
2.代碼,讀取本地圖片儲存在byte[]中,付給實體類的picture字段,調用 hibernate的save方法保存
/** * hibernate保存圖片到數據表 */ @Transactional(readOnly = false) public void hibsaveImage(GoodsPic gp, String path) {//GoodsPic為圖片實體類,path為圖片所在磁盤的路徑 try { InputStream in = null; in = new FileInputStream(path); byte[] b = new byte[in.available()]; in.read(b); in.close(); gp.setPicture(b); myDao.save(gp); } catch (Exception e) { e.printStackTrace(); } }
[spring如何啟動的?這里結合spring源碼描述了啟動過程](https://www.cnblogs.com/demingblog/p/7443714.html)
[SpringMVC是怎么工作的,SpringMVC的工作原理](https://www.cnblogs.com/demingblog/p/9925268.html)
[spring 異常處理。結合spring源碼分析400異常處理流程及解決方法](https://www.cnblogs.com/demingblog/p/9218271.html)
[Mybatis Mapper接口是如何找到實現類的-源碼分析](https://www.cnblogs.com/demingblog/p/9544774.html)
[使用Netty實現HTTP服務器](https://www.cnblogs.com/demingblog/p/9970772.html)
[Netty實現心跳機制](https://www.cnblogs.com/demingblog/p/9957143.html)
[Netty系列](https://www.cnblogs.com/demingblog/p/9912099.html)
