日期:2014-05-16  浏览次数:20277 次

jsp + struts上传

jsp代码
注意,form的enctype和input的type
<form name="baseInfoForm" method="post"
enctype="multipart/form-data" id="form1">
<input type="file" name="pic" />
</form>

struts-config.xml
动态表单的类型设置,注意看类型
<form-bean name="baseInfoForm"
         type="org.apache.struts.action.DynaActionForm">
   <form-property name="pic" type ="org.apache.struts.upload.FormFile"/>


java处理
//----------开始上传照片-------------------------
  ///debug
  System.out.println(BaseInfoAction.class.getClassLoader().getResource(""));
  System.out.println(ClassLoader.getSystemResource(""));
  System.out.println(BaseInfoAction.class.getResource(""));
  System.out.println(BaseInfoAction.class.getResource("/")); //Class文件所在路径
  System.out.println(new File("/").getAbsolutePath());
  System.out.println(System.getProperty("user.dir"));

  //end debug

  FormFile file= (FormFile)dynaActionForm.get("pic"); 
  //存储目录
  if(file != null){
   //获得图片存储路径
 
   String fileName = file.getFileName();
   if(!fileName.equalsIgnoreCase("")){
    String fileType = fileName.substring(fileName.indexOf("."));
    String picName = code + fileType;
  
    BufferedImage   sourceImg   =   javax.imageio.ImageIO.read(file.getInputStream());
    int height = sourceImg.getHeight();
    int width = sourceImg.getWidth();
    int size = file.getFileSize();
  
  
    String dir = servlet.getServletContext().getRealPath("/web/upload/photos");
    //String dir = request.getContextPath();
    String fileDir = dir + "\\" +  code + fileType;
    //String fileDir =  "C:\\Program Files\\Apache Software Foundation\\Tomcat5.5\\webapps\\TeacherInfo\\web\\upload\\photos\\" + picName;
    //String fileDir =  System.getProperty("user.dir") + "\\WebContent\\web\\upload\\photos\\" + code + fileType;
    //String fileDir = request.getContextPath() + "/web/upload/photos/" + picName;
  
    InputStream in = file.getInputStream();
    OutputStream out = new FileOutputStream(fileDir);
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    while((bytesRead=in.read(buffer,0,8192)) != -1){
     out.write(buffer,0,bytesRead);
    }
    out.close();
    in.close();
    file.destroy();
  
    //图片路径存进数据库
    dbaseInfo.setT09(request.getContextPath() + "/web/upload/photos/" + picName);
    tableOpGenericDAO.update(dbaseInfo);
  
上传组件

struts包 包含了这个org.apache.struts.upload就可以上传。