spring上传单个文件与多个文件

 

用spring操作上传附件ResourceManageImple.class:

package

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import FileCommonOper;
import ResourceFile;
public class ResourceManageImple{
public final static SYS_WS_ADD_ATTACHMENT_PREFIX="add_attachment_id";
 /**
  *
  */
 private static final Log log = LogFactory.getLog(ResourceManageImple.class);
    /**
     *
     */
    private String directory = "C:/temp";
    /**
     *
     */
 private ResourceManageDao resourceManageDao;
 
  /**
   * 得到服务器系统年-天-小时-秒


   * @return String
   */
  private String getServerSysDateAndTimeAsCode(){
    String result=null;
    java.util.Date currentDate=null;
    java.text.SimpleDateFormat df=null;
    String yearAndMonth=null;
    //年-天-小时-秒
    df=new java.text.SimpleDateFormat("yyyyMMddHHmmssSS");
    currentDate=new java.util.Date();
    yearAndMonth=df.format(currentDate);
    result=yearAndMonth;
    return result;
  }
 
  /**
   * 下载文件
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public int downloadFile(HttpServletRequest request,
    HttpServletResponse response)  throws java.lang.Exception{
   int resultInt=-1;
   String resourceID = request.getParameter("resourceID");
   String fileFullPathName=null;
   String filePath=null;
   if (resourceID != null && !resourceID.equals("")) {
    ResourceFile fileDes = resourceManageDao.findById(resourceID);
    if (fileDes != null) {
     String contentType = "application/octet-stream";
     response.setContentType(contentType);
     // formData.getResponse().set

     InputStream is = null;
     OutputStream os = null;
     try {
      response.setHeader("Content-disposition",
        "attachment;filename=/""
          + new String(fileDes.getOrgFileName().getBytes(), "iso8859-1") + "/"");
      filePath=fileDes.getFilePath();
      fileFullPathName=getDirectory()+ filePath;
      is = new BufferedInputStream(new FileInputStream(fileFullPathName));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      os = new BufferedOutputStream(response.getOutputStream());
      byte[] buffer = new byte[4 * 1024];
      int read = 0;
      while ((read = is.read(buffer)) != -1) {
       baos.write(buffer, 0, read);
      }
      os.write(baos.toByteArray());
     } catch (IOException e) {
      e.printStackTrace();
     } finally {
      try {
       if(os!=null){
         os.close();
       }
       if(is!=null){
         is.close();
       }
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }

     }
    }
   }
   resultInt=1;
   return resultInt;
  }
  /**
     * 上传资源文件
     * @param request
     * @param resourceFile
     * @param resourceFileExtend 禁止上传扩展文件名的文件
     * @return
     * @throws java.lang.Exception
     */
  public Hashtable saveFile(HttpServletRequest request
      ,ResourceFile  resourceFile,ResourceFileExtend resourceFileExtend)throws java.lang.Exception{
   if (request instanceof MultipartHttpServletRequest) {
    return saveFiles((MultipartHttpServletRequest) request,resourceFile);
   } else {
    MultipartResolver resolver = new CommonsMultipartResolver(request
      .getSession().getServletContext());
    try {
     MultipartHttpServletRequest mrequest = resolver
       .resolveMultipart(request);
     return saveFiles(mrequest, resourceFile);
    } catch (MultipartException e) {
     throw new Exception(e);
    }
   }
     }   
  /**
   * 删除资源文件
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public int deleteFile(String resourceID) throws java.lang.Exception{
   String[] resourceIDArr=null;
   resourceIDArr=new String[1];
   resourceIDArr[0]=resourceID;
   return deleteFile(resourceIDArr);
  } 
  /**
   * 删除多个资源文件
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public int deleteFile(String[] resourceIDArr) throws java.lang.Exception{  
   int resultInt=-1;
   ResourceFile  resourceFile=null; 
   String resourceID=null;
   try{
             if((resourceIDArr!=null)&&(resourceIDArr.length>0)){
              for(int i=0;i<resourceIDArr.length;i++){
               resourceFile=new ResourceFile();
               resourceID=resourceIDArr[i];
            resourceFile.setResourceID(resourceID);
            resourceManageDao.delete(resourceFile);
              }
             }
             resultInt=1;
   }
   catch(java.lang.Exception ex){
    throw ex;
   }  
   return resultInt;
  }
 
  /**
   * 删除资源文件的时候是否删除实际的文件
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public int deleteFile(String resourceID,boolean isDeleteRealFile) throws java.lang.Exception{
   return -1;
  } 
  /**
   * 删除多个资源文件的时候是否删除实际的文件
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public int deleteFile(String[] resourceIDArr,boolean isDeleteRealFile) throws java.lang.Exception{
   return -1;
  }
  /**
   *
   * @param resourceID
   * @return
   * @throws java.lang.Exception
   */
  public ResourceFile findById(String resourceID) throws java.lang.Exception{
   return null;
  }
 /**
  * hash表中保存的是(控件名,资源id)
  * @param request
  * @param parentPath
  * @param userId
  * @return
  * @throws java.lang.Exception
  */
   public Hashtable saveFile(HttpServletRequest request
     ,ResourceFile  resourceFile)throws java.lang.Exception{
   return saveFile(request,resourceFile,null);
   }
  
   /**
    *
    * @param request
    * @param parentPath
    * @param userId
    * @return
    */
   private Hashtable saveFiles(MultipartHttpServletRequest request
     ,ResourceFile resourceFile) throws java.lang.Exception{
     MultipartHttpServletRequest q = (MultipartHttpServletRequest) request;
   if (q.getContentType().toLowerCase().indexOf("multipart/form-data") != -1) {
       String parentPath=null;
       String userId=null;
       String flag=null;
       String appId=null;
       String proceedingCode=null;
       String modifier=null;
       if(resourceFile!=null){
        parentPath=resourceFile.getParentPath();
        userId=resourceFile.getCreator();
        flag=resourceFile.getFlag();
        appId=resourceFile.getAppId();
        proceedingCode=resourceFile.getProceedingCode();
        modifier=resourceFile.getModifier();
       }
       parentPath=StrOperate.checkNull(parentPath,"");
       userId=StrOperate.checkNull(userId,"");
       flag=StrOperate.checkNull(flag,"");
       appId=StrOperate.checkNull(appId,"");
       proceedingCode=StrOperate.checkNull(proceedingCode,"");
       modifier=StrOperate.checkNull(modifier,"");
    // 使用随机文件名
    String fileName = getServerSysDateAndTimeAsCode();
    FileCommonOper fileCommonOper=null;
    String tempDir=null;
    fileCommonOper=FileCommonOper.getInstance();
    tempDir=directory;
    fileCommonOper.newFolder(tempDir);
    if (parentPath != null) {
     tempDir=directory + "//" + parentPath;
     fileCommonOper.newFolder(tempDir);
    }
    Iterator it = q.getFileNames();
    MultipartFile file;
    String ext;
    String controlName;
    String orgFileName;
    int i = 1;
    ResourceFile resource = null;
    Hashtable ret = new Hashtable();
    List resourceList = new ArrayList();
    String destFileName=null;
    String title=null;
    try {
      while (it.hasNext()) {
       //得到控件名
     controlName = it.next().toString();
     file = q.getFile(controlName);
     title=(String)q.getParameter(SYS_WS_ADD_ATTACHMENT_PREFIX+controlName);
     if(title==null){
      title="";
     }
     if (file.getSize() > 0) {
      orgFileName = file.getOriginalFilename();
      ext = orgFileName.indexOf(".") == -1 ? "" : orgFileName
        .substring(orgFileName.lastIndexOf("."),orgFileName.length());
      resource = new ResourceFile();
      resource.setOrgFileName(file.getOriginalFilename());
                            //写文件
       byte[] by = file.getBytes();
       FileOutputStream fos = null;
       destFileName=fileName + i + ext;
       if (parentPath == null) {
        fos = new FileOutputStream(directory + "//"+ destFileName);
       } else {
        fos = new FileOutputStream(directory + "//"+ parentPath + "//" + destFileName);
       }
       fos.write(by);
       fos.flush();
       fos.close();
       //end;       
      
      if(userId.length()!=0){
        resource.setCreator(userId);
        resource.setCreatTime(getServerCurrentSysDateAndTime());
      }
      else{
       if(modifier.length()!=0){
         resource.setModifier(modifier);
         resource.setLastModifyTime(getServerCurrentSysDateAndTime());
       }
       else{
         resource.setCreatTime(getServerCurrentSysDateAndTime());
       }
      }
      resource.setFilePath("//" + parentPath + "//" + fileName+ i  + ext);
      resource.setFlag(flag);
      resource.setAppId(appId);
      resource.setProceedingCode(proceedingCode);
      resource.setFileSize(new Long(file.getSize()));
      resource.setFileSuffix(ext);
      resource.setDestFileName(destFileName);
      resource.setTitle(title);
      resourceList.add(resource);    
      
      ret.put(controlName, resource);
      i++;
     }
      }
    } catch (IOException e) {
     throw new Exception("Write to Resource File Store error", e);
    }

    for(Iterator iterator=resourceList.iterator();iterator.hasNext();){
     resource=(ResourceFile)iterator.next();
     resourceManageDao.save(resource);
    }
    return ret;
   } else {
    throw new Exception("Not Support such kind servlet");
   }

  }
  
   /**
   * 得到服务器系统日期和时间
   * @return String
   */
  public static String getServerCurrentSysDateAndTime(){
    String pattern="yyyy-MM-dd HH:mm:ss";
    String result=null;
    java.text.SimpleDateFormat df=null;
    df=new java.text.SimpleDateFormat(pattern);
    result=df.format(new java.util.Date());
   
    return result;
  }
 
 
 public String getDirectory() {
  return directory;
 }

 public void setDirectory(String directory) {
  this.directory = directory;
 }


 public ResourceManageDao getResourceManageDao() {
  return resourceManageDao;
 }
 public void setResourceManageDao(ResourceManageDao resourceManageDao) {
  this.resourceManageDao = resourceManageDao;
 }
}

 

 

 

 

 

 

 

 

 

 

文件操作util类FileCommonOper .class;

package

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCommonOper {
   private static Log logger= LogFactory.getLog(FileCommonOper.class);
  
 
   /**
    *
    *
    */
   private FileCommonOper() {
   }

   /**
    *
    * @return
    */
     public static FileCommonOper getInstance(){
    return new FileCommonOper();
   }
 /**
    * 新建目录
    * @param folderPath String 如 c:/wy
    * @return boolean
    */
   public void newFolder(String folderPath) throws Exception{
    String filePath = folderPath;
       File myFilePath =null;   
     try {      
       if(filePath!=null){
        filePath = filePath.toString();
        myFilePath = new File(filePath);
        //如果该目录不存在,则创建之
        if (myFilePath.exists()==false) {
          myFilePath.mkdirs();
        }
       }
     }
     catch (Exception e) {
       logger.error("directory create fail,dir is:"+folderPath);
       throw e;
     }
     finally{
      myFilePath=null;
     }
   }
   /**
    * 新建文件
    * @param filePathAndName String 文件路径及名称 如c:/wy.txt
    * @param fileContent String 文件内容
    * @return boolean
    */
   public void newFile(String filePathAndName, String fileContent) {

     try {
       String filePath = filePathAndName;
       filePath = filePath.toString();
       File myFilePath = new File(filePath);
       if (!myFilePath.exists()) {
         myFilePath.createNewFile();
       }
       FileWriter resultFile = new FileWriter(myFilePath);
       PrintWriter myFile = new PrintWriter(resultFile);
       String strContent = fileContent;
       myFile.println(strContent);
       resultFile.close();
     }
     catch (Exception e) {
       logger.error("新建目录操作出错");
       e.printStackTrace();
     }
   }
   /**
    * 删除文件
    * @param filePathAndName String 文件路径及名称 如c:/wy.txt
    * @param fileContent String
    * @return boolean
    */
   public void delFile(String filePathAndName) {
     try {
       String filePath = filePathAndName;
       filePath = filePath.toString();
       File myDelFile = new File(filePath);
       myDelFile.delete();
     }
     catch (Exception e) {
       logger.error("删除文件操作出错");
       e.printStackTrace();
     }
   }
   /**
    * 删除文件夹

    * @param filePathAndName String 文件夹路径及名称 如c:/wy
    * @param fileContent String
    * @return boolean
    */
   public void delFolder(String folderPath) {
     try {
       //delAllFile(folderPath); //删除完里面所有内容

       String filePath = folderPath;
       filePath = filePath.toString();
       File myFilePath = new File(filePath);
       myFilePath.delete(); //删除空文件夹

     }
     catch (Exception e) {
       System.out.println("删除文件夹操作出错");
       e.printStackTrace();
     }
   }
 /**
    * 复制单个文件
    */
   public void copyFile(String oldPath, String newPath) throws Exception {
    int bytesum = 0;
       int byteread = 0;
       InputStream inStream =null;
       FileOutputStream fs =null;
       byte[] buffer =null;
       File oldfile =null;
     try {     
      logger.debug("copy file in");
       oldfile = new File(oldPath);
       if ((oldfile!=null)&&(oldfile.exists()==true) ){
       logger.debug("copy file exists");
         inStream = new FileInputStream(oldPath);        
         fs = new FileOutputStream(newPath);
         buffer = new byte[2048];
      logger.debug("copy file begin");
         while ( (byteread = inStream.read(buffer)) != -1) {
           bytesum += byteread;           
           fs.write(buffer, 0, byteread);
         }
            fs.flush();
       }
     }
     catch (Exception ex) {
      throw ex;
     } 
     finally{      
      try{
       if(fs!=null){
        fs.close();
       }
      }
      catch (Exception fex) {
       fs=null;
      }
      try{
       if(inStream!=null){
              inStream.close();
       }
      }
      catch (Exception inex) {
      }
     }    
   }


}

 

 

资源文件实体类,ResourceFile .class:

package ;

 
/**
 *
 * @author lin
 *
 */
public class ResourceFile {

 public ResourceFile() {
 }
 /**
  *
  */
 private String parentPath;
 /**
  * 资源id
  */
 private String resourceID;
    /**
     * 文件存放路径,相对于文件存放根目录
     */
    private String filePath;
    /**
     * 上传时候的主题
     */
    private String title;
    /**
     * 文件后缀
     */
    private String fileSuffix;
 /**
  * 文件的描述信息
  */
 private String filedesc="";
 /**
  * 原文件名
  */
 private String orgFileName;

 /**
  * 转换后的文件名

  */
 private String destFileName;

 /**
  * 创建者

  */
 private String creator;

 /**
  * 创建时间
  */
 private String creatTime;

 
 /**
  * 修改者

  */
 private String modifier;
 /**
  * 文件大小
  */
 private Long fileSize;
 /**
  * 修改时间
  */
 private String lastModifyTime;
    /**
     *
     */
 private String proceedingCode;
 /**
  *
  */
 private String appId;
 
 /**
  * 用于标记是注册用户注册时候上传的文件,还是申报用户申报数据时候上传的文件
  * r:注册用户注册时候上传的文件
  * a:申报用户申报数据时候上传的文件
  */
 private String flag;
 
 public String getAppId() {
  return appId;
 }

 public void setAppId(String appId) {
  this.appId = appId;
 }

 public String getDestFileName() {
  return destFileName;
 }

 public void setDestFileName(String destFileName) {
  this.destFileName = destFileName;
 }

 public String getFilePath() {
  return filePath;
 }

 public void setFilePath(String filePath) {
  this.filePath = filePath;
 }

 public Long getFileSize() {
  return fileSize;
 }

 public void setFileSize(Long fileSize) {
  this.fileSize = fileSize;
 }

 public String getFileSuffix() {
  return fileSuffix;
 }

 public void setFileSuffix(String fileSuffix) {
  this.fileSuffix = fileSuffix;
 }

 public String getFlag() {
  return flag;
 }

 public void setFlag(String flag) {
  this.flag = flag;
 }

 public String getProceedingCode() {
  return proceedingCode;
 }

 public void setProceedingCode(String proceedingCode) {
  this.proceedingCode = proceedingCode;
 }

 /**
  * @return Returns the creat_time.
  */
 public String getCreatTime() {
  return creatTime;
 }

 /**
  * @param creat_time The creat_time to set.
  */
 public void setCreatTime(String creat_time) {
  this.creatTime = creat_time;
 }


 /**
  * @return Returns the modifier.
  */
 public String getModifier() {
  return modifier;
 }

 /**
  * @param modifier The modifier to set.
  */
 public void setModifier(String modifier) {
  this.modifier = modifier;
 }

 

 public String getFiledesc() {
  return filedesc;
 }

 public void setFiledesc(String filedesc) {
  this.filedesc = filedesc;
 }

 public String getCreator() {
  return creator;
 }

 public void setCreator(String creator) {
  this.creator = creator;
 }

 public String getLastModifyTime() {
  return lastModifyTime;
 }

 public void setLastModifyTime(String lastModifyTime) {
  this.lastModifyTime = lastModifyTime;
 }

 public String getOrgFileName() {
  return orgFileName;
 }

 public void setOrgFileName(String orgFileName) {
  this.orgFileName = orgFileName;
 }

 public String getResourceID() {
  return resourceID;
 }

 public void setResourceID(String resourceID) {
  this.resourceID = resourceID;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getParentPath() {
  return parentPath;
 }

 public void setParentPath(String parentPath) {
  this.parentPath = parentPath;
 }

 
}

 

hibernate配置文件

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ucap.jet.util.resource.spring.entity">
  <class name="ResourceFile" table="JET_SYS_RESOURCE_FILE">
    <id name="resourceID" column="resourceID" type="string">
      <generator class="uuid.hex" />
    </id>
    <property name="title" column="title" type="string" />   
    <property name="orgFileName" column="ORgFILENAME" type="string" />
    <property name="filedesc" column="filedesc" type="string" />
    <property name="destFileName" column="destFileName" type="string" />
    <property name="filePath" column="filePath" type="string" />
    <property name="fileSuffix" column="fileSuffix" type="string" />   
    <property name="flag" column="flag" type="string" />
    <property name="creator" column="creator" type="string" />
    <property name="creatTime" column="CREATTIME" type="string" />
    <property name="modifier" column="modifier" type="string" />
    <property name="lastModifyTime" column="lastModifyTime" type="string" />
    <property name="appId" column="appId" type="string" />
    <property name="proceedingCode" column="proceedingCode" type="string" />
    <property name="fileSize" column="fileSize" type="long" />       
  </class>
</hibernate-mapping>

spring的powercontext文件上传附件配置:

<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="10240000"/>
           <property name="maxInMemorySize">
              <value>1024000</value>
           </property>
        </bean>



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1733869

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值