1. 程式人生 > >Spring MVC上傳圖片,Java二進位制圖片寫入資料庫,生成略縮圖

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

步驟: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 類 ,詳細情況檢視:

@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();
        }
}