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

你可能感兴趣的:(java,文件上传 springmvc)