Spring MVC上傳圖片,Java二進位圖片寫入資料庫,產生縮圖

最近做到一個專案,有個商品記錄功能。記錄的內容包括:商品基本資訊(文字);圖片資訊,並要求將圖片保存到資料表中的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();
        }

    }

留言

這個網誌中的熱門文章

TeknoParrot 模擬器介紹,俗稱《鸚鵡模擬器》

[轉貼] ASP.NET傳遞參數給Crystal Report做Export或Print的動作

[轉貼] Server 端Post資料到 .ashx