熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

struts實現多圖片上傳

2022-06-13   來源: Java開源技術 

  package comninetownszhangcstrutsaction;

  public class Constant {

  private Constant() {

  }

  public static Integer pictureSize = **;   //單位為byte   上傳文件最大限額

  public static String  pictureDirectory = upload\\;

  }

  package comninetownszhangcstrutsaction;

  import javaioFile;

  import javaioFileOutputStream;

  import javaioInputStream;

  import javaioOutputStream;

  import javautilCollection;

  import javautilHashtable;

  import javautilIterator;

  import javautilregexMatcher;

  import javautilregexPattern;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsuploadFormFile;

  import orgapachestrutsuploadMultipartRequestHandler;

  public class PictureUpLoad {

  private PictureUpLoad() {

  }

  private static boolean isValidFile(String fileName) {

  String[] validFiles = { gif jpg jpeg jpe bmp pngtxt/plaintextdocrar };

  boolean ret = false;

  for (int i = ; i < validFileslength; i++) {

  if (fileNametoLowerCase()endsWith(validFiles[i])) {

  ret = true;

  break;

  }

  }

  return ret;

  }

  private static String rebuildFileName(String fileName) {

  javatextSimpleDateFormat sdf = new javatextSimpleDateFormat(

  yyyyMMddHHmmss);

  javautilDate date = new javautilDate();

  return sdfformat(date) + _ + fileName;

  }

  private static String lianjieFileName(String fileName){

  return  +fileName;

  }

  private static boolean isDirectoryExists(String path){

  javaioFile file = new File(path);

  if(!fileexists()){

  return filemkdir();

  }else

  return true;

  }

  private static String[] getFileName(String filesName){

  Pattern x=pile(\\w*\\s+\\w*);

  String[] fileName = filesNamesplit(\\s+);

  Matcher t = xmatcher(filesName);

  Systemoutprintln(  tmatches());

  return fileName;

  }

  public static String[] fileUpLoad(ActionForm form

  HttpServletRequest request HttpServletResponse response)

  throws Exception {

  String path = ;

  String fileName = ;

  MultipartRequestHandler handle = formgetMultipartRequestHandler();

  Hashtable hashTable = handlegetFileElements();

  Collection cln = hashTablevalues();

  Iterator iterator = erator();

  while (iteratorhasNext()) {

  FormFile file = (FormFile) iteratornext();

  path = requestgetRealPath(/) + ConstantpictureDirectory;

  if(isDirectoryExists(path)==false) return null;

  if (filegetFileName() == null)

  return null;

  if (filegetFileSize() > ConstantpictureSize)

  return null;

  if (!isValidFile(filegetContentType()))

  return null;

  try {

  InputStream in = filegetInputStream();

  OutputStream out = new FileOutputStream(path

  + rebuildFileName(filegetFileName()));// /表示保存的路徑可以修改為load/

  int bytesRead = ;

  byte[] buffer = new byte[];

  while ((bytesRead = inread(buffer  )) != ) {

  outwrite(buffer  bytesRead);

  }

  outclose();

  inclose();

  } catch (Exception e) {

  eprintStackTrace();

  }

  fileName=fileName+lianjieFileName(rebuildFileName(filegetFileName()));

  }

  return getFileName(fileName);

  }

  }

  package comninetownszhangcstrutsaction;

  import javaioFileOutputStream;

  import javaioInputStream;

  import javaioOutputStream;

  import javautilCollection;

  import javautilHashtable;

  import javautilIterator;

  import javaxservlethttpHttpServletRequest;

  import javaxservlethttpHttpServletResponse;

  import orgapachestrutsactionAction;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionForward;

  import orgapachestrutsactionActionMapping;

  import orgapachestrutsuploadFormFile;

  import orgapachestrutsuploadMultipartRequestHandler;

  import comninetownszhangcstrutsformUploadForm;

  /**

  * MyEclipse Struts Creation date: 

  *

  * XDoclet definition:

  *

  * @strutsaction input=newjsp validate=true

  * @strutsactionforward name=list path=listjsp 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 Autogenerated method stub

  UploadForm updForm = (UploadForm)form;

  try {

  String[] fileNames = PictureUpLoadfileUpLoad(updForm request response);

  requestsetAttribute(fileNames fileNames);

  Systemoutprintln(=========+fileNameslength);

  for(String file:fileNames){

  Systemoutprintln(filename   +file);

  }

  } catch (Exception e) {

  // TODO Autogenerated catch block

  eprintStackTrace();

  }

  return mappingfindForward(index);

  }

  }

  package comninetownszhangcstrutsform;

  import javaxservlethttpHttpServletRequest;

  import orgapachestrutsactionActionErrors;

  import orgapachestrutsactionActionForm;

  import orgapachestrutsactionActionMapping;

  /**

  * MyEclipse Struts

  * Creation date: 

  *

  * XDoclet definition:

  * @strutsform 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 Autogenerated method stub

  return null;

  }

  /**

  * Method reset

  * @param mapping

  * @param request

  */

  public void reset(ActionMapping mapping HttpServletRequest request) {

  // TODO Autogenerated 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) {

  thisname = name;

  }

  }

  indexjsp

  <%@ page language=java pageEncoding=GBK%>

  <!DOCTYPE HTML PUBLIC //WC//DTD HTML  Transitional//EN>

  <html>

  <head>

  <title>struts upload by zhangc</title>

  </head>

  <body>

  <a >create</a><br>

  </body>

  </html>

  newjsp

  <%@ page language=java pageEncoding=GBK%>

  <%@ taglib uri=/WEBINF/strutsbeantld prefix=bean%>

  <%@ taglib uri=/WEBINF/strutshtmltld prefix=html%>

  <html>

  <head>

  <title>struts upload by zhangc</title>

  <script language=javascript>

  var rnum = ;

  function addRow()

  {

  var oT = documentgetElementById(oTable);

  var newTR = oTinsertRow(oTrowslength);

  newTRid = row + rnum;

  var newTD = newTRinsertCell();

  var newTD = newTRinsertCell();

  newTDsetAttribute(colSpan);

  newTDinnerText = file;

  newTDinnerHTML = <input name=\file

  + rnum

  + \ type=\file\ > <input name=\del\ type=\button\ value=\刪除 \ onClick=\deleteRow( + rnum +);\>;

  rnum++;

  }

  function deleteRow(line)

  {

  oTabledeleteRow(documentgetElementById(row + line)rowIndex);

  }

  </script>

  </head>

  <body>

  <form name=updForm method=post action=uploaddo enctype=multipart/formdata>

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

  nextjsp

  <%@ page language=java import=javautil* pageEncoding=ISO%>

  <%@ taglib prefix=c uri=javasun/jsp/jstl/core%>

  <%

  String path = requestgetContextPath() + /upload;

  String basePath = requestgetScheme() + ://

  + requestgetServerName() + : + requestgetServerPort()

  + path + /;

  %>

  <!DOCTYPE HTML PUBLIC //WC//DTD HTML  Transitional//EN>

  <html>

  <head>

  <base <%=basePath%>>

  <title>My JSP nextjsp starting page</title>

  <meta httpequiv=pragma content=nocache>

  <meta httpequiv=cachecontrol content=nocache>

  <meta httpequiv=expires content=>

  <meta httpequiv=keywords content=keywordkeywordkeyword>

  <meta httpequiv=description content=This is my page>

  <!

  <link rel=stylesheet type=text/css >

  >

  </head>

  <body>

  <c:forEach var=fileName items=${fileNames} begin=>

  <img alt= width= height= src=<%=basePath%>${fileName}>

  </c:forEach>

  </body>

  </html>

  <?xml version= encoding=UTF?>

  <!DOCTYPE strutsconfig PUBLIC //Apache Software Foundation//DTD Struts Configuration //EN /struts/dtds/strutsconfig__dtd>

  <strutsconfig>

  <datasources />

  <formbeans >

  <formbean name=uploadForm type=comninetownszhangcstrutsformUploadForm />

  </formbeans>

  <globalexceptions />

  <globalforwards />

  <actionmappings >

  <action

  input=newjsp

  path=/upload name=uploadForm

  type=comninetownszhangcstrutsactionUploadAction

  scope=request>

  <forward

  name=index

  path=/nextjsp/>

  </action>

  </actionmappings>

  <messageresources parameter=comninetownszhangcstrutsApplicationResources />

  </strutsconfig>


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28037.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.