EXTjs+SpringMVC+Mybatis实现照片的上传,下载,查看关键技术整理

第一个问题:如何通过Extjs4实现照片上传的布局展示以及本地照片选择后的在一个区域内进行图片预览

实现照片上传的布局展示:

items : [ {
                        xtype : ‘box‘,
                        itemId : ‘imageShow‘,
                        id:‘imageShow‘,
                        border : 1,
                        style : {
                            borderColor : ‘#99bbe8‘,
                            borderStyle : ‘solid‘,
                        },
                        margin : ‘0 0 5 55‘,
                        autoEl : {
                            width : 105,
                            height : 128,
                            tag : ‘img‘,
                            //style : ‘filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);‘,
                            complete : ‘off‘,
                            src : ‘images/blank.jpg‘,
                        }
                    }, {
                        xtype : ‘filefield‘,
                        name : ‘imageFile‘,
                        itemId:‘imageFile‘,
                        id:‘person_imageFile‘,
                        labelWidth : 50,
                        width : 200,
                        fieldLabel : ‘照片‘,
                        allowBlank : false,
                        buttonText: ‘‘,
                        buttonConfig: {
                            iconCls: ‘upload-icon‘
                        }
                    } ]

显示的样式为:

 

第二个问题:如何在chrome中选择本地的照片后进行图片的预览:(对file控件进行监控)

‘#personWindow #imageFile‘ : {
                change : this.handlerImageFile
            },
handlerImageFile:function(view,value){
        var file=Ext.query(‘#person_imageFile input[type=file]‘)[0];
        var img=view.previousSibling().getEl().dom;
          var reader = new FileReader();
          reader.onload = function(evt){img.src = evt.target.result;}
          reader.readAsDataURL(file.files[0]);
    },

 

第三个问题:如何跟SpringMVC结合保存照片呢?

1.含有照片的form,必须要通过form.submit来进行提交:

savePersonAction:function(button,urlString){
        var form = button.up(‘window‘).down(‘form‘).getForm();
        form.submit({
            clientValidation : true,
            url : urlString,
            params : {
                // newStatus: ‘delivered‘
            },
            scope : this,// 使回调函数中的this变成当前的类
            success : function(form, action) {
                if (action.result.success == ‘true‘) {
                    Ext.Msg.alert(‘系统提示‘, action.result.msg,function(){
                        button.up(‘window‘).hide();
                        this.refreshGrid();
                    },this);
                } else {
                    Ext.Msg.alert(‘系统提示‘, action.result.errorMsg);
                }
            },
        });
    }

 

2.在spring的配置文件中增加配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="100000"/>
        <property name="maxInMemorySize" value="4096" />
    </bean>

 

3.在bean中增加配置

private Date csrq;
    private String jtzz;
    private String bz;
    private Integer photoId;
    private CommonsMultipartFile imageFile;//上传的文件

 

4.使用bean来接受参数:

@ResponseBody
    @RequestMapping("/userManage/person/insertPerson")
    public String insertPerson(SysPersonModel sysPersonModel) {
        Map resultMap = new HashMap();
        try {
            sysPersonService.insertPerson(sysPersonModel);
            resultMap.put("success", "true");
            resultMap.put("msg", "保存成功");
        } catch (ApplicationException e) {
            resultMap.put("success", "ApplicationException");
            resultMap.put("errorMsg", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("success", "Exception");
            resultMap.put("errorMsg", e.getMessage());
        }

        return JSON.toJSONString(resultMap);
    }

 

第四个问题:如何在Mybatis中进行文件的保存和查看呢?

1.增加Photo相关的Bean以及Mapper类,以及sql文件:

package cn.telchina.standard.entity;

public class PhotoModel {
    private Integer photoId;
    private String photoName;
    private Object photo;

    public Integer getPhotoId() {
        return photoId;
    }

    public void setPhotoId(Integer photoId) {
        this.photoId = photoId;
    }

    public String getPhotoName() {
        return photoName;
    }

    public void setPhotoName(String photoName) {
        this.photoName = photoName;
    }

    public Object getPhoto() {
        return photo;
    }

    public void setPhoto(Object photo) {
        this.photo = photo;
    }

}

 

package cn.telchina.standard.mapper;

import java.util.List;

import cn.telchina.standard.entity.PhotoModel;

public interface PhotoMapper {

    public int getPhotoId();

    public void createPhoto(PhotoModel photoModel);

    public int deletePhoto(int photoId);

    public int updatePhoto(PhotoModel photo);

    public  List<PhotoModel> getPhotoForUpdate(int photoId);

    public  List<PhotoModel> getPhoto(int photoId);

}

 

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.telchina.standard.mapper.PhotoMapper">
    <!-- <![CDATA[sql 尽量每个sql必须写,防止有些特殊字符对sql语句造成的破坏 -->
    <select id="getPhotoId" resultType="int">
        <![CDATA[
        select base.seq_photo.nextval id from dual
        ]]>
    </select>

    <insert id="createPhoto" parameterType="PhotoModel">
        <![CDATA[
        INSERT INTO base.PHOTO(photoid,photoname,photo)
            VALUES(#{photoId},#{photoName, jdbcType=VARCHAR}, empty_blob())
         ]]>
    </insert>  

     <select id="getPhotoForUpdate" resultType="PhotoModel">
        SELECT photoid,
               photo,
               photoname
          FROM base.PHOTO
         WHERE photoid = #{photoId} for update
    </select>

    <delete id="deletePhoto" >
        DELETE FROM base.PHOTO
              WHERE PHOTO_ID = #{photoId}
    </delete>  

    <update id="updatePhoto" parameterType="PhotoModel" >
        UPDATE base.PHOTO
           SET photoname = #{photoName, jdbcType=VARCHAR}
         WHERE photoid = #{photoId}
    </update>  

    <select id="getPhoto" resultType="PhotoModel">
        SELECT photoid,
               photo,
               photoname
          FROM base.PHOTO
         WHERE photoid = #{photoId}
    </select>
</mapper>

2.在service中增加新增照片的代码:

@Transactional(rollbackFor = Exception.class)
    public void insertPerson(SysPersonModel sysPersonModel)
            throws ApplicationException {
        this.checkPersonByRybh(sysPersonModel.getRybh());
        this.checkPersonBySfzhm(sysPersonModel.getSfzhm());

        int photoId = photoMapper.getPhotoId();
        String fileName = sysPersonModel.getImageFile().getOriginalFilename();

        PhotoModel photoModel = new PhotoModel();
        photoModel.setPhotoId(photoId);
        photoModel.setPhotoName(fileName);

        photoMapper.createPhoto(photoModel);

        updatePhoto(sysPersonModel, photoId);

        sysPersonModel.setPhotoId(photoId);

        sysPersonMapper.insertPerson(sysPersonModel);
    }

private void updatePhoto(SysPersonModel sysPersonModel, Integer photoId) {
        List<PhotoModel> list = photoMapper.getPhotoForUpdate(photoId);
        PhotoModel newPhotoModel = list.get(0);

        BLOB photo = (BLOB) newPhotoModel.getPhoto();

        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(
                    photo.getBinaryOutputStream());// 暂时使用这个废弃的方法
            // ops = content.setBinaryStream(0);//ojdbc14支持,ojdbc6,5都不支持
            in = new BufferedInputStream(
                    (FileInputStream) sysPersonModel.getImageFile()
                            .getInputStream());
            byte[] data = FileCopyUtils.copyToByteArray(in);
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3文件的展示和下载:

前台代码:

//进入新增页面时初始化默认头像
    initImageSrc:function(view){
        if(view.down(‘#imageShow‘).getEl()){
            var img=view.down(‘#imageShow‘).getEl().dom;
            img.src=‘images/blank.jpg‘;
        }
    },
//查看
    showImg:function(view,photoId){
        if(photoId!=""){
            var img=view.down(‘#imageShow‘).getEl().dom;
            img.src=‘userManage/person/showPhoto.json?photoId=‘+photoId;
        }else{
            this.initImageSrc(view);
        }
    },
//下载
downFileButtonHandler:function(button){
        var sm = button.up(‘#datagrid‘).getSelectionModel();
        if (sm.getCount() == 0) {
            Ext.Msg.alert(‘系统提示‘, "修改人员信息前先选中一条记录!");
        } else {
            var record = sm.getSelection()[0];
            var photoId=record.data.photoId;
            if(photoId!=""){
                window.open(‘userManage/person/downFile.json?photoId=‘+photoId,"_self");
            }else{
                Ext.Msg.alert(‘系统提示‘, "该人员没有头像!");
            }

        }
    },
@ResponseBody
    @RequestMapping(value = "/userManage/person/showPhoto")
    public void showPhoto(Integer photoId, HttpServletResponse response) {
        OutputStream outputStream = null;
        InputStream in = null;
        try {
            PhotoModel photoModel = sysPersonService.getPhotoById(photoId);

            BLOB photo = (BLOB) photoModel.getPhoto();

            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            in = new BufferedInputStream(photo.getBinaryStream());

            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
        } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                in.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    @ResponseBody
    @RequestMapping(value = "/userManage/person/downFile")
    public void downFile(Integer photoId, HttpServletResponse response) {
        OutputStream outputStream = null;
        InputStream in = null;

        try {
            PhotoModel photoModel = sysPersonService.getPhotoById(photoId);

            BLOB photo = (BLOB) photoModel.getPhoto();

            // byte[] data=photo.getBytes();

            String fileName = photoModel.getPhotoName() == null ? "照片.jpg"
                    : photoModel.getPhotoName();
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + fileName + "\"");
            response.addHeader("Content-Length", "" + photo.length());
            response.setContentType("application/octet-stream;charset=UTF-8");

            in = new BufferedInputStream(photo.getBinaryStream());
            outputStream = new BufferedOutputStream(response.getOutputStream());

            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
        } catch (ApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                in.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
时间: 2024-10-13 00:04:48

EXTjs+SpringMVC+Mybatis实现照片的上传,下载,查看关键技术整理的相关文章

CentOS里上传下载查看命令

由于每次在CentOS中要下载一些配置文件到物理机,和上传一些文件到虚拟机,导致来回的开启ftp软件有点麻烦,这里用两个命令工具,来解决可以随意的上传和下载. 安装软件包: [[email protected] ~]# yum -y install lrzsz Loaded plugins: fastestmirror, refresh-packagekit, security Loading mirror speeds from cached hostfile * base: mirrors.

SpringMVC(6)文件上传

SpringMVC(6)文件上传 我们做一个上传图片的例子,页面(fileUpload.jsp)功能如下: 上传成功后即时显示上传的图片. upload.jsp: <body> <h3>文件上传</h3> <form action="/testAnnotationMVC_fileUpload/file/fileUpload2.jspx" method="post" enctype="multipart/form-d

SpringMVC文件上传下载

在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/qixiaoyizhan/p/5819392.html 今天我们来讲讲spring mvc中的文件上传和下载的几种方法. 首先附上文件目录->我们需要配置的我做了记号-> 一.文件上传 首先为了方便后续的操作,以及精简代码,我们在Utils包下封装一个文件上传下载的帮助类: Files_Helper

SSM框架-SpringMVC 实例文件上传下载

SSM框架-SpringMVC 实例文件上传下载 2017-04-17 09:38 4497人阅读 评论(6) 收藏 举报  分类: java基础(3)  目录(?)[+] 目录(?)[+] 林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文详细讲解了SpringMVC实例单文件上传.多文件上传.文件列表显示.文件下载. 本文工程免费下载 一.新建一个Web工程,导入相关的包 springmvc的包+commons-fileupload

SpringMVC上传下载

springmvc上传下载功能 参照网上代码写了一个简单的例子 1.需要导入jar包:ant.jar.commons-fileupload.jar.connom-io.jar.当然spring jar包不可缺少的哦  我这里用的是spring+springmvc+hibernate  可以到官网上直接下载springmvcjar即可 2.springmvc.xml配置 <?xml version="1.0" encoding="UTF-8"?> <

SpringMVC中的多文件上传

这是用的是SpringMVC-3.1.1.commons-fileupload-1.2.2和io-2.0.1 首先是web.xml <?xml version="1.0" encoding="UTF-8"?>   <web-app version="2.5"        xmlns="http://java.sun.com/xml/ns/javaee"        xmlns:xsi="http

SpringMVC注解方式与文件上传

目录: springmvc的注解方式 文件上传(上传图片,并显示) 一.注解 在类前面加上@Controller 表示该类是一个控制器在方法handleRequest 前面加上 @RequestMapping("/index") 表示路径/index会映射到该方法上 将上一篇的博客改为注解方式: SpringMVC的基础配置及视图定位 1.修改springmvc-servlet.xml 去掉映射相关的配置,因为已经使用注解方式了增加 <context:component-scan

SpringMVC+Mybatis框架整合源码 项目 下载 rest websocket html5

获取[下载地址]   QQ: 313596790   [免费支持更新]A 代码生成器(开发利器);全部是源码     增删改查的处理类,service层,mybatis的xml,SQL( mysql   和oracle)脚本,   jsp页面 都生成   就不用写搬砖的代码了,生成的放到项目里,可以直接运行B 阿里巴巴数据库连接池druid;  数据库连接池  阿里巴巴的 druid.Druid在监控.可扩展性.稳定性和性能方面都有明显的优势C 安全权限框架shiro ;  Shiro 是一个用

SpringMVC+Mybatis框架整合源码 项目 下载 rest websocket html5 自定义表单

获取[下载地址]   [免费支持更新]三大数据库 mysql  oracle  sqlsever   更专业.更强悍.适合不同用户群体[新录针对本系统的视频教程,手把手教开发一个模块,快速掌握本系统] A 集成代码生成器 [正反双向(单表.主表.明细表.树形表,开发利器)+快速构建表单; freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本,处理类,service等完整模块B 集成阿里巴巴数据库连接池druid;  数据库连接池  阿里巴巴的 druid.Dr