springmvc 文件上传、下载、预览。以二进制形式存放到数据库。
数据库中的关于传入附件的字段我写了2个:一个存放内容accessory,一个存放文件的后缀filetype

上传:首先需要2个必须的jar:
commons.io-1.4.0.jar
commons.fileupload-1.2.0.jar

XXX-servlet.xml中写入上传拦截:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolve">  
      <property name="maxUploadSize" value="100000" />  
</bean>

jsp页面:
<form method="POST" action="提交地址" name="frm" enctype="multipart/form-data">   
       <input type="file" name="accessory"/><br>  
        <input type="submit" onclick="return checkacc();"/><br>  
</form>
<!--如果需要验证传入的文件的类型,可以通过js验证,我这个是在提交的时候验证的-->
<!--
function checkacc(){
    var postfix = frm.accessory.value.substring(frm.accessory.value.lastIndexOf(".")+1); //获得选择的上传文件的后缀名的正则表达式  
     if(postfix!=""){
          if(!(postfix == "jpg"||postfix == "pdf"))   
          {   
      alert('文件类型不正确,请选择.jpg或者.pdf文件 !');   
      document.getElementById('accessory').value="";
      document.getElementById('accessory').focus();
      return false;   
          }  
     } 
}
-->

注:在以前用servlet写的文件上传,加入enctype="multipart/form-data"这个字段,会造成获取不到form内其他字段的值,但在springmvc中不会出现这个问题。

java Controller类:
public ModelAndView addSaleStock(HttpServletRequest request,HttpServletResponse response) throws Exception {
       MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;
       MultipartFile file = multipartRequest.getFile("accessory");
       byte[] inputData = null;
       String fileType="";
       if(file!=null){
             inputData = inputStream2Byte(file.getInputStream());
             String s=file.getOriginalFilename();
             fileType=s.substring(s.lastIndexOf(".")+1);
                }        
                 //数据库中表的对象类(model),通俗说就是hibernate中的po
                 ValidRegstock validRegstock = new ValidRegstock();
                 validRegstock.setInputData(inputData);
                 validRegstock.setFiletype(fileType);
                      try {
                             //去看service类
            this.getBeanOfValidRegstockService().addSendRegStock(validRegstock);
           msg = "添加成功!";
             } catch (Exception e) {
           e.printStackTrace();
            msg = "添加失败!";
             }
                  return new ModelAndView(返回地址);
}

java service类:
public void addSendRegStock(ValidRegstock validRegstock)
throws Exception {
   //去看dao类
   regStockDao.add(validRegstock);
}

java  dao类:
public void add(ValidRegstock validRegstock) {
       String sql="insert into Z_ValidRegstock(accessory,filetype) values(?,?)";
       //这里我们用数据连接的形式存入数据库
       Connection conn=null;
       try {
conn = getJdbcTemplate().getDataSource().getConnection();
PreparedStatement ps=conn.prepareStatement(sql);
          //注意 :大对象类型的 我们存入的是bytes[],这里要set object
ps.setObject(1, validRegstock.getInputData());
ps.setString(2, validRegstock.getFiletype());
ps.executeUpdate();
conn.commit();
ps.close();
conn.close();
       } catch (SQLException e) {
e.printStackTrace();
       }
}

这样就能上传了。需要注意的是:

有些朋友会用:
Object[] params={validRegstock.getInputData()};
int[] dataTypes={Types.XXX};
getJdbcTemplate().update( sql, params, dataTypes);
这种方法存入,这里我之所以用了Types.XXX是因为 我试过Types.blob,Types.other等等都不好使。并且我把bytes[]用hibernate转为java.sql.blob的存入的话 也是不好使的。会出现类型不匹配java.oracle.blob.所以有用这种方法成功的朋友请告诉我。谢谢

预览和下载差不多。同一个service,同一个dao,我先给出dao和service:
java dao类:
public List accessorySel(String id){
StringBuffer sql=new StringBuffer("");
sql.append("select accessory,filetype from Z_ValidRegstock where regstockId='");
sql.append(id);
sql.append("'");
Connection conn=null;
statement state=null;
ResultSet rs = null;
List list=new ArrayList();
try {
    conn=getJdbcTemplate().getDataSource().getConnection();
    state=conn.createStatement();
    rs=state.executeQuery(sql.toString());
    if (rs.next()) {
                   //这个blob是java.sql.Blob类型的
Blob blob = rs.getBlob("accessory");
String filetype=rs.getString("filetype");
list.add(0, blob);
list.add(1,filetype);
    }
} catch (SQLException e) {
    e.printStackTrace();
          }
return list;
}

java service类:
public List accessorySel(String id){
return regStockDao.accessorySel(id);
}

java Controller类:
预览:
public ModelAndView getAccessoryView(HttpServletRequest request,HttpServletResponse response) throws Exception {
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
int length = (int) blob.length();
byte[] bImage = new byte[length];
InputStream is = new BufferedInputStream(blob.getBinaryStream());
is.read(bImage, 0, length);
OutputStream out = response.getOutputStream(); 
out.write(bImage);
out.flush(); 
out.close();
is.close();
return null;
}

下载:
public ModelAndView getAccessoryDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
         //jsp传过来的 要下载附件对应数据的id
String id=request.getParameter("id");
List list=this.getBeanOfValidRegstockService().accessorySel(id);
Blob blob=(Blob) list.get(0);
String filetype=(String) list.get(1);
OutputStream fos = response.getOutputStream();
InputStream is = new BufferedInputStream(blob.getBinaryStream());
          //如果下载的是表格形式的,可能会出现乱码。加入下面这句话:(其他出现乱码的情况自己百度下。)
response.setHeader("Content-Type","application/vnd.ms-excel");
//弹出保存框的语句,后面可以填入默认名称和类型
          response.setHeader("Content-Disposition","Attachment;filename=accessory."+filetype);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = is.read(buffer)) != -1) {
      fos.write(buffer, 0, size);
}
      fos.flush();
      fos.close();
      return null;
}
}

springmvc 文件下传、上载、预览。以二进制形式存放到数据库(转载)的更多相关文章

  1. JavaScrip 原生多文件上传及预览 兼容多浏览器

    JavaScrip 原生多文件上传及预览 兼容多浏览器 html代码块 <div class="container"> <label>请选择一个图像文件:& ...

  2. form表单系列中文件上传及预览

    文件上传及预览 Form提交 Ajax 上传文件 时机: 如果发送的[文件]:->iframe, jQurey(),伪Ajax 预览 import os img_path = os.path.j ...

  3. 结合bootstrap fileinput插件和Bootstrap-table表格插件,实现文件上传、预览、提交的导入Excel数据操作流程

    1.bootstrap-fileinpu的简单介绍 在前面的随笔,我介绍了Bootstrap-table表格插件的具体项目应用过程,本篇随笔介绍另外一个Bootstrap FieInput插件的使用, ...

  4. servlet实现文件上传,预览,下载和删除

      一.准备工作 1.1 文件上传插件:uploadify: 1.2 文件上传所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar 1.3 将数 ...

  5. form里面文件上传并预览

    其实form里面是不能嵌套form的,如果form里面有图片上传和其他input框,我们希望上传图片并预览图片,然后将其他input框填写完毕,再提交整个表单的话,有两种方式! 方式一:点击上传按钮的 ...

  6. JQ图片文件上传之前预览功能

    1.先准备一个div onchange触发事件 <input  type="file" onchange="preview(this)" >< ...

  7. Django的文件上传以及预览、存储

    思路: 文件上传通过前端的input标签,input设置display:none属性. 内容显示需要让前端通过<img>标签读取图片内容,可以通过<label>标签连接< ...

  8. 支持多文件上传,预览,拖拽,基于bootstra的上传插件fileinput 的ajax异步上传

    首先需要导入一些js和css文件 <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...

  9. 支持多文件上传,预览,拖拽,基于bootstrap的上传插件fileinput 的ajax异步上传(转载)

    首先需要导入一些js和css文件 <link href="__PUBLIC__/CSS/bootstrap.css" rel="stylesheet"&g ...

随机推荐

  1. 解决pydev无法增加jython271 interpreter的问题

    ============================解决pydev无法增加jython271 interpreter的问题============================ 从jython. ...

  2. TCP的流模式与UDP的报文模式对比

    1       案例背景 在学习TCP-IP协议详解卷一时,读到介绍TCP协议的部分,发现TCP的首部是没有报文总长度字段的,而在UDP中是有的,对这个问题的思考引出了两者之间的区别. 2    案例 ...

  3. POJ 1061 青蛙的约会

                            青蛙的约会 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 82859   A ...

  4. I’ve seen the world,lit it up as my stage now

    I've seen the world,lit it up as my stage now 阅尽繁华 点亮红尘做舞台 Channeling angels in,the new age now 粉末登场 ...

  5. PPPoE名词解释

    PPPoE拔号的发现阶段(Discovery): PPPoE的发现阶段一共分为4步. 分别是: PADI(PPPoE Active Discovery Initiation) PADO(PPPoE A ...

  6. 原生态js,鼠标按下后,经过了那些单元格

    本来是要判断那些单元格被选中,结果发现行不通,只能判断鼠标按下后,经过了那些单元格 之所以发出来,是觉得案例还有很多有意思的地方 onmouseover  的持续触发,导致了很多重复元素 由于将事件绑 ...

  7. 如何根据屏幕大小改变class的css样式

    /*当屏幕小于1200px*/ @media (max-width:1200px) { ...} 此处针对所有小于1200px屏幕的css属性. /*当屏幕小于1200px且大于992px*/ @me ...

  8. UOJ25——IOI2014Wall

    1.题目大意:这道题也是线段树修改,有两种修改,一个区间中大于h都变成h,一个区间中小于h都变成h,单点询问 主要是这几种操作 2.分析:这道题是双标记,还是父亲的优先级比儿子低,自己用手推推就可以知 ...

  9. leetcode 33. Search in Rotated Sorted Array

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

  10. 联合主键用Hibernate注解映射的三种方式

    第一.将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并重写equals和hascode,再将该类注解为@Embeddable,最后在主类中(该类不包含联合主 ...