博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring MVC上传图片,Java二进制图片写入数据库,生成略缩图
阅读量:7281 次
发布时间:2019-06-30

本文共 4506 字,大约阅读时间需要 15 分钟。

背景描述:最近做到一个项目,有个商品登记功能。登记的信息包括:基本信息若干(文字信息);图片信息,要求将图片保存到数据表中的image字段(sql server 数据库)

步骤:1.将图片上传到服务器的一个磁盘目录下。

        2.将刚才上传好的图片写入数据库image字段。

一、上传图片:使用的是spring mvc 对上传的支持。

jsp 页面

spring_mvc.xml配置

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

 

 

[](https://www.cnblogs.com/demingblog/p/7443714.html)

[](https://www.cnblogs.com/demingblog/p/9925268.html)
[](https://www.cnblogs.com/demingblog/p/9218271.html)

[](https://www.cnblogs.com/demingblog/p/9544774.html)

[](https://www.cnblogs.com/demingblog/p/9970772.html)
[(https://www.cnblogs.com/demingblog/p/9957143.html)
[](https://www.cnblogs.com/demingblog/p/9912099.html)

 

转载于:https://www.cnblogs.com/demingblog/archive/2013/02/25/2932161.html

你可能感兴趣的文章
关于开源的RTP——jrtplib的使用
查看>>
mac osx voice over的使用
查看>>
【Tools】maven安装
查看>>
每日一句(2014-9-11)
查看>>
【BZOJ】1665: [Usaco2006 Open]The Climbing Wall 攀岩(spfa)
查看>>
最长上升(不下降)子序列(详细,转)
查看>>
EF 6 调用存储过程时返回多结果集和OUTPUT参数问题
查看>>
oracle调优 浅析关联设计
查看>>
@功能的逻辑判断(原创)
查看>>
java异常处理
查看>>
SQL Server 的三种用户自定义函数
查看>>
nodejs文件操作笔记
查看>>
零零散散学算法之具体解释几种最短路径
查看>>
BDB (Berkeley DB)数据库简单介绍(转载)
查看>>
一款基于css3非常实用的鼠标悬停特效
查看>>
分布式存储系统sheepdog
查看>>
Ecshop与Jquery冲突的完美解决方案
查看>>
SQL Server 数据库设计规范
查看>>
sql server 2005 32位+64位、企业版+标准版、CD+DVD 下载地址大全
查看>>
Android中Application类用法
查看>>