程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> struts實現多圖片上傳

struts實現多圖片上傳

編輯:關於JAVA

package com.ninetowns.zhangc.struts.action;
public class Constant {

  private Constant() {

  }
  public static Integer pictureSize = 10*1024*1024;   //單位為byte   上傳文件最大限額;
  public static String  pictureDirectory = "upload\\";
}

package com.ninetowns.zhangc.struts.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
public class PictureUpLoad {
  private PictureUpLoad() {
  }
  private static boolean isValidFile(String fileName) {
   String[] validFiles = { "gif", "jpg", "jpeg", "jpe", "bmp", "png","txt/plain","text","doc","rar" };
   boolean ret = false;
   for (int i = 0; i < validFiles.length; i++) {
    if (fileName.toLowerCase().endsWith(validFiles[i])) {
     ret = true;
     break;
    }
   }
   return ret;
  }
  private static String rebuildFileName(String fileName) {
   java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
     "yyyyMMddHHmmss");
   java.util.Date date = new java.util.Date();
   return sdf.format(date) + "_" + fileName;
  }

  private static String lianjieFileName(String fileName){
   return " "+fileName;
  }
  private static boolean isDirectoryExists(String path){
   java.io.File file = new File(path);
   if(!file.exists()){
      return file.mkdir();
   }else
    return true;
  }
  private static String[] getFileName(String filesName){
    Pattern x=Pattern.compile("\\w*\\s+\\w*");  
     String[] fileName = filesName.split("\\s+");
     Matcher t = x.matcher(filesName);
     System.out.println(  t.matches());
   return fileName;
  }

  public static String[] fileUpLoad(ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {
   String path = "";
   String fileName = "";
   MultipartRequestHandler handle = form.getMultipartRequestHandler();
   Hashtable hashTable = handle.getFileElements();
   Collection cln = hashTable.values();
   Iterator iterator = cln.iterator();
   while (iterator.hasNext()) {
    FormFile file = (FormFile) iterator.next();
    path = request.getRealPath("/") + Constant.pictureDirectory;
    if(isDirectoryExists(path)==false) return null;
    if (file.getFileName() == null)
     return null;
    if (file.getFileSize() > Constant.pictureSize)
     return null;
    if (!isValidFile(file.getContentType()))
     return null;
    try {
     InputStream in = file.getInputStream();
     OutputStream out = new FileOutputStream(path
       + rebuildFileName(file.getFileName()));// "/"表示保存的路徑可以修改為"load/"
     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();
    } catch (Exception e) {
     e.printStackTrace();
    }
    fileName=fileName+lianjieFileName(rebuildFileName(file.getFileName()));
   }
   return getFileName(fileName);
  }
}

package com.ninetowns.zhangc.struts.action;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
import com.ninetowns.zhangc.struts.form.UploadForm;
/**
  * MyEclipse Struts Creation date: 10-18-2006
  *
  * XDoclet definition:
  *
  * @struts.action input="new.jsp" validate="true"
  * @struts.action-forward name="list" path="list.jsp" redirect="true"
  */
public class UploadAction extends Action {
   /*
    * Generated Methods
    */
   /**
    * Method execute
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return ActionForward
    */
   public ActionForward execute(ActionMapping mapping, ActionForm form,
     HttpServletRequest request, HttpServletResponse response) {
    // TODO Auto-generated method stub
    UploadForm updForm = (UploadForm)form;
    try {
   String[] fileNames = PictureUpLoad.fileUpLoad(updForm, request, response);
   request.setAttribute("fileNames", fileNames);
   System.out.println("========="+fileNames.length);
   for(String file:fileNames){
    System.out.println("filename   "+file);
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    return mapping.findForward("index");
   }
  }

package com.ninetowns.zhangc.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
/**
  * MyEclipse Struts
  * Creation date: 10-18-2006
  *
  * XDoclet definition:
  * @struts.form name="uploadForm"
  */
public class UploadForm extends ActionForm {
  /*
   * Generated fields
   */
  /** name property */
  private String name;
  /*
   * Generated Methods
   */
  /**
   * Method validate
   * @param mapping
   * @param request
   * @return ActionErrors
   */
  public ActionErrors validate(ActionMapping mapping,
    HttpServletRequest request) {
   // TODO Auto-generated method stub
   return null;
  }
  /**
   * Method reset
   * @param mapping
   * @param request
   */
  public void reset(ActionMapping mapping, HttpServletRequest request) {
   // TODO Auto-generated method stub
  }
  /**
   * Returns the name.
   * @return String
   */
  public String getName() {
   return name;
  }
  /**
   * Set the name.
   * @param name The name to set
   */
  public void setName(String name) {
   this.name = name;
  }
}

index.jsp

<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
   <head>
    <title>struts upload by zhangc</title>
   </head>

   <body>
     <a href="new.jsp">create</a><br>
   </body>
</html>

new.jsp

<%@ page language="java" pageEncoding="GBK"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<html>
  <head>
   <title>struts upload by zhangc</title>
    <script language="javascript">
    var rnum = 1;
    function addRow()
    {
     var oT = document.getElementById("oTable");
     var newTR = oT.insertRow(oT.rows.length-1);
     newTR.id = "row" + rnum;
     var newTD0 = newTR.insertCell();
     var newTD1 = newTR.insertCell();

     newTD1.setAttribute("colSpan","2");

     newTD0.innerText = "file:";
     newTD1.innerHTML = "<input name=\"file"
          + rnum
          + "\" type=\"file\" > <input name=\"del\" type=\"button\" value=\"刪除 \" onClick=\"deleteRow(" + rnum +");\">";
     rnum++;
    }
    function deleteRow(line)
    {
      oTable.deleteRow(document.getElementById("row" + line).rowIndex);
    }
   </script>
  </head>
  <body>
   <form name="updForm" method="post" action="upload.do" enctype="multipart/form-data">
   <table id="oTable">
    <tr>
    <td>name:</td>
    <td><input name="name" type="text"></td>
    </tr>
    <tr>
      <td>上傳圖片:</td>
    <td><input type=file name="temp">        <input type="button" name="add" value="多圖片上傳 " onClick="addRow()"></td>
    </tr>
    <tr>
    <td><input name="sub" type="submit" value=" 上傳 "></td>
    </tr>
   </table>
   </form>
  </body>
</html>

next.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
  String path = request.getContextPath() + "/upload";
  String basePath = request.getScheme() + "://"
    + request.getServerName() + ":" + request.getServerPort()
    + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <base href="<%=basePath%>">
   <title>My JSP 'next.jsp' starting page</title>
   <meta http-equiv="pragma" content="no-cache">
   <meta http-equiv="cache-control" content="no-cache">
   <meta http-equiv="expires" content="0">
   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
   <meta http-equiv="description" content="This is my page">
   <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
  </head>
  <body>
   <c:forEach var="fileName" items="${fileNames}" begin='1'>
    <img alt="" width="300" height="200" src="<%=basePath%>${fileName}">
   </c:forEach>
  </body>
</html>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
   <data-sources />
   <form-beans >
     <form-bean name="uploadForm" type="com.ninetowns.zhangc.struts.form.UploadForm" />

   </form-beans>
   <global-exceptions />
   <global-forwards />
   <action-mappings >
     <action
       input="new.jsp"
       path="/upload" name="uploadForm"
       type="com.ninetowns.zhangc.struts.action.UploadAction"
       scope="request">
       <forward
         name="index"
         path="/next.jsp"/>
     </action>

   </action-mappings>
   <message-resources parameter="com.ninetowns.zhangc.struts.ApplicationResources" />
</struts-config>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved