Multiple pictures Upload Simple example

Source: Internet
Author: User

Said is original, in fact, is also a reference to a number of online posts, very grateful to those who selfless dedication of the predecessors!

This project is to use the FileUpload package and related IO package (I uploaded to the Internet, you can download for free),

In addition, you can also use STRUTS2 package, in order to save trouble I put the whole struts2-core-2.3.24.1 package into the project, the package contains all the packages to upload.

STRUTS2 package can be downloaded from official website: http://struts.apache.org/download.cgi#struts23241


1, upload a number of pictures is to pay attention to

First: <form id= "Form1" Name= "Form1" method= "Post" action= ". /servlet/fileservlet "

Enctype= "Multipart/form-data" >

In the "enctype=" Multipart/form-data "" is necessary to write.

Second: <input name= "file" type= "file" size= "multiple/>"

In the "multiple" must be written, or can only be a radio. Note: Multiple this attribute is only supported after HTML5

Directory Structure ***************************

See "Blog Attachment"

The code is as follows:

JSP Code ***************************************

index.jsp Code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "

pageencoding= "UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title>insert title here</title>

<body>

<a href= "upload/upload2.jsp" > multiple file uploads </a>

</body>


///////////////////////////////////////////////////////

UPLOAD2.JSP code (the interface for uploading files)

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "

pageencoding= "UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title> multiple photo uploads </title>

<body>

<a href= ". /index.jsp "> Home </a>


<p align= "center" > Please select the file you want to upload </p>

<form id= "Form1" Name= "Form1" method= "Post" action= ". /servlet/fileservlet "enctype=" Multipart/form-data ">

Upload file: <input name= "file" type= "file" size= "multiple/>"

<br>

<input type= "submitted" name= "submit" value= "Submission" >

<input type= "reset" name= "reset" value= "reset" >

<br>

</form>

</body>

/////////////////////////////////////////////////////////////////

UPLOADRESULT.JSP code (the interface that displays the results of the upload)

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "

pageencoding= "UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title>uploadResult</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" >

-


<body>

${requestscope[' Upload.message '}

<a href= ". /upload/upload2.jsp "> Upload file </a>

</body>

Web. XML **********************************

Web. XML code

<?xml version= "1.0" encoding= "UTF-8"?>

<web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 ">

<display-name>fileUp1</display-name>

<servlet>

<servlet-name>FileUploadServlet</servlet-name>

<servlet-class>com.li.servlet.FileUploadServlet</servlet-class>

<init-param>

<param-name>savePath</param-name>

<param-value>D:/uploads</param-value>

</init-param>

</servlet>


<servlet-mapping>

<servlet-name>FileUploadServlet</servlet-name>

<url-pattern>/servlet/fileServlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

Servlet Code ***************************

Fileuploadservlet.java

Package com.li.servlet;


Import Java.io.File;

Import java.io.IOException;

Import Java.util.Iterator;

Import java.util.List;


Import Javax.servlet.ServletConfig;

Import Javax.servlet.ServletContext;

Import javax.servlet.ServletException;

Import Javax.servlet.annotation.WebServlet;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;


Import Org.apache.commons.fileupload.FileItem;

Import org.apache.commons.fileupload.FileUploadException;

Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

Import Org.apache.struts2.ServletActionContext;


/**

* Servlet Implementation Class Fileuploadservlet

*/

@WebServlet ("/fileuploadservlet")

public class Fileuploadservlet extends HttpServlet {

Private static final long serialversionuid = 1L;

Private ServletContext SC;

Private String Savepath;

Private File Uploadpath;

public void doget (HttpServletRequest request, httpservletresponse response)

Throws Servletexception, IOException {

DoPost (request, response);

}


public void init (ServletConfig config) {

An initialization parameter set in Web. xml

Savepath = Config.getinitparameter ("Savepath");

sc = Config.getservletcontext ();

Uploadpath = new File (GetPath ());

When initializing, check the folder where the pictures are uploaded and the folder where the temporary files are stored, and if they do not exist, create

if (!uploadpath.exists ()) {

Uploadpath.mkdir ();

}

}


public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {

Request.setcharacterencoding ("UTF-8");

Diskfileitemfactory factory = new Diskfileitemfactory ();

Servletfileupload upload = new Servletfileupload (factory);

try {

List items = upload.parserequest (request);

Iterator ITR = Items.iterator ();

while (Itr.hasnext ()) {

Fileitem item = (Fileitem) itr.next ();

if (Item.isformfield ()) {

System.out.println ("form argument name:" + item.getfieldname () + ", form parameter value:" + item.getstring ("UTF-8"));

} else {

if (item.getname () = null &&!item.getname (). Equals ("")) {

SYSTEM.OUT.PRINTLN ("Size of uploaded file:" + item.getsize ());

System.out.println ("Type of upload file:" + Item.getcontenttype ());

Item.getname () returns the full path name of the uploaded file on the client

System.out.println ("Name of the uploaded file:" + item.getname ());

File Tempfile = new file (Item.getname ());

Save path of uploaded file

File File = new file (GetPath (), Tempfile.getname ());

Item.write (file);

Request.setattribute ("Upload.message", "Upload file succeeded!") ");

}else{

Request.setattribute ("Upload.message", "no option to upload files!") ");

}

}

}

}catch (Fileuploadexception e) {

E.printstacktrace ();

} catch (Exception e) {

E.printstacktrace ();

Request.setattribute ("Upload.message", "Upload file failed!") ");

}

Request.getrequestdispatcher (".. /upload/uploadresult.jsp "). Forward (request, response);

}

Public String GetPath () {

Return Savepath.indexof (":") >0?savepath:sc.getrealpath ("/") + Savepath;

}

}

The above code can be saved under the specified drive letter or on the server, just change the parameters of Web. xml;

The disadvantage of putting on the server is that it is easy to cause the previous picture to be lost when the server is re-arranged and the file is not backed up in time.


Multiple pictures Upload Simple example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.