Several common file upload in jsp and struts Methods
Advertisements
File upload in web applications are very common in the environment to achieve jsp file upload feature is very easy, because there are many web development with java file upload component, this paper commons-fileupload component, for example, is Add file upload jsp application.
common-fileupload component is an open source one of apache, you can download from the http://jakarta.apache.org/commons/fileupload/. The component can be achieved with one or more files once uploaded, and can limit the file size.
You must extract the zip package, commons-fileupload-1.0.jar will be copied to tomcat's webapps \ your webapp \ WEB-INF \ lib \, the directory does not exist, please self-built directory.
Create a new servlet: Upload.java for file uploads:
Java code
- public class Upload extends HttpServlet {
- private String uploadPath = "C: \ \ upload \ \"; / / upload files
- private String tempPath = "C: \ \ upload \ \ tmp \ \"; / / temporary file directory
- public void doPost (HttpServletRequest request,
- HttpServletResponse response)
- throws IOException, ServletException
- {
- }
- }
- In the doPost () method, when the servlet receives a browser request issued by the Post, the implementation file upload. The following is a sample code:
- public void doPost (HttpServletRequest request,
- HttpServletResponse response)
- throws IOException, ServletException
- {
- try {
- DiskFileUpload fu = new DiskFileUpload ();
- / / Set the maximum file size, here is the 4MB
- fu.setSizeMax (4194304);
- / / Set the buffer size, this is 4kb
- fu.setSizeThreshold (4096);
- / / Set the temporary directory:
- fu.setRepositoryPath (tempPath);
- / / Get all the files:
- List fileItems = fu.parseRequest (request);
- Iterator i = fileItems.iterator ();
- / / Process each file in turn:
- while (i.hasNext ()) {
- FileItem fi = (FileItem) i.next ();
- / / Get the file name, the file name including the path:
- String fileName = fi.getName ();
- / / Here the user can record and file information
- / / ...
- / / Write to file, the file named interim a.txt, can be extracted from the file name fileName:
- fi.write (new File (uploadPath + "a.txt"));
- }
- }
- catch (Exception e) {
- / / Error page you can jump
- }
- }
- If you want to read the configuration file specified in the upload folder in the init () method implementation:
- public void init () throws ServletException {
- uploadPath = ....
- tempPath = ....
- / / Folder does not exist are automatically created:
- if (! new File (uploadPath). isDirectory ())
- new File (uploadPath). mkdirs ();
- if (! new File (tempPath). isDirectory ())
- new File (tempPath). mkdirs ();
- }
public class Upload extends HttpServlet {
private String uploadPath = "C:\\upload\\"; // Upload files
private String tempPath = "C:\\upload\\tmp\\"; // Temporary file directory
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
}
}
In doPost() Method, when servlet Post received the browser request issued , For file uploads. The following is a sample code :
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
try {
DiskFileUpload fu = new DiskFileUpload();
// Set the maximum file size, this is 4MB
fu.setSizeMax(4194304);
// Set the buffer size, this is 4kb
fu.setSizeThreshold(4096);
// Temporary directory :
fu.setRepositoryPath(tempPath);
// Get all the files :
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// Processes each file in turn :
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// Access to the file name, the file name including path :
String fileName = fi.getName();
// Here you can record the user and file information
// ...
// Written to the file, the file named interim a.txt, Can be extracted from the file name fileName :
fi.write(new File(uploadPath + "a.txt"));
}
}
catch(Exception e) {
// Error page can jump
}
}
If you want to read the configuration file specified in the upload folder, you can init() Method of execution :
public void init() throws ServletException {
uploadPath = ....
tempPath = ....
// Folder does not exist to automatically create :
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if(!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
}
Compile the servlet, note to specify classpath, be sure to include commons-upload-1.0.jar and the tomcat \ common \ lib \ servlet-api.jar.
Configuration servlet, use Notepad to open the tomcat \ webapps \ your webapp \ WEB-INF \ web.xml, if not, create a new one.
A typical configuration is as follows:
Web.xml code
- <? Xml version = "1.0" encoding = "ISO-8859-1"?>
- <! DOCTYPE web-app
- PUBLIC "- / / Sun Microsystems, Inc. / / DTD Web Application 2.3 / / EN"
- "Http://java.sun.com/dtd/web-app_2_3.dtd">
- <web-app>
- <servlet>
- <servlet-name> Upload </ servlet-name>
- <servlet-class> Upload </ servlet-class>
- </ Servlet>
- <servlet-mapping>
- <servlet-name> Upload </ servlet-name>
- <url-pattern> / fileupload </ url-pattern>
- </ Servlet-mapping>
- </ Web-app>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
</web-app>
Configured servlet, start the tomcat, write a simple html test:
Struts Code
- <Form action = "fileupload" method = "post"
- enctype = "multipart / form-data" name = "form1">
- <input type="file" name="file">
- <input type="submit" name="Submit" value="upload">
- </ Form>
<form action="fileupload" method="post" enctype="multipart/form-data" name="form1"> <input type="file" name="file"> <input type="submit" name="Submit" value="upload"> </form>
Note that action = "fileupload" which fileupload servlet is configured when the specified url-pattern.
II:
Select upload page: selfile.jsp, so visit this page:
Jsp code
- <html:link module="/upload" page="/upload.do"> continue to upload </ html: link> </ h2>
- -------------------------------------------------- ------------------------------
- <% @ Page contentType = "text / html; charset = GBK"%>
- <% @ Page import = "org.apache.struts.action .*,
- java.util.Iterator,
- org.apache.struts.Globals "%>
- <% @ Taglib uri = "/ tags / struts-bean" prefix = "bean"%>
- <% @ Taglib uri = "/ tags / struts-html" prefix = "html"%>
- <% @ Taglib uri = "/ tags / struts-logic" prefix = "logic"%>
- <logic:messagesPresent>
- <ul>
- <html:messages>
- <li> <bean:write name="error"/> </ li>
- </ Html: messages>
- </ Ul> <hr />
- </ Logic: messagesPresent>
- <html:html>
- <html:form action="uploadsAction.do" enctype="multipart/form-data">
- <html:file property="theFile"/>
- <html:submit/>
- </ Html: form>
- </ Html: html>
<html:link module="/upload" page="/upload.do"> Continue to upload </html:link></h2>
--------------------------------------------------------------------------------
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="org.apache.struts.action.*,
java.util.Iterator,
org.apache.struts.Globals" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<logic:messagesPresent>
<ul>
<html:messages>
<li><bean:write name="error"/></li>
</html:messages>
</ul><hr />
</logic:messagesPresent>
<html:html>
<html:form action="uploadsAction.do" enctype="multipart/form-data">
<html:file property="theFile"/>
<html:submit/>
</html:form>
</html:html>
Form bean: UpLoadForm.java
Java code
- package org.apache.struts.webapp.upload;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts.action .*;
- import org.apache.struts.upload .*;
- / **
- * <p> Title: UpLoadForm </ p>
- * <p> Description: QRRSMMS </ p>
- * <p> Copyright: Copyright (c) 2004 jiahansoft </ p>
- * <p> Company: jiahansoft </ p>
- * @ Author wanghw
- * @ Version 1.0
- * /
- public class UpLoadForm extends ActionForm {
- public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";
- protected FormFile theFile;
- public FormFile getTheFile () {
- return theFile;
- }
- public void setTheFile (FormFile theFile) {
- this. theFile = theFile;
- }
- public ActionErrors validate (
- ActionMapping mapping,
- HttpServletRequest request) {
- ActionErrors errors = null;
- / / Has the maximum length been exceeded?
- Boolean maxLengthExceeded =
- (Boolean) request.getAttribute (
- MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
- if ((maxLengthExceeded! = null) & & (maxLengthExceeded.booleanValue ())) {
- errors = new ActionErrors ();
- errors.add (
- ActionMessages.GLOBAL_MESSAGE,
- new ActionMessage ("maxLengthExceeded"));
- errors.add (
- ActionMessages.GLOBAL_MESSAGE,
- new ActionMessage ("maxLengthExplanation"));
- }
- return errors;
- }
- }
package org.apache.struts.webapp.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.*;
/**
* <p>Title:UpLoadForm</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) 2004 jiahansoft</p>
* <p>Company: jiahansoft</p>
* @author wanghw
* @version 1.0
*/
public class UpLoadForm extends ActionForm {
public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";
protected FormFile theFile;
public FormFile getTheFile() {
return theFile;
}
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = null;
//has the maximum length been exceeded?
Boolean maxLengthExceeded =
(Boolean) request.getAttribute(
MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
errors = new ActionErrors();
errors.add(
ActionMessages.GLOBAL_MESSAGE ,
new ActionMessage("maxLengthExceeded"));
errors.add(
ActionMessages.GLOBAL_MESSAGE ,
new ActionMessage("maxLengthExplanation"));
}
return errors;
}
}
Handling uploaded files: UpLoadAction.java
Java code
- package org.apache.struts.webapp.upload;
- import java.io. *;
- import javax.servlet.http .*;
- import org.apache.struts.action .*;
- import org.apache.struts.upload.FormFile;
- / **
- * <p> Title: UpLoadAction </ p>
- * <p> Description: QRRSMMS </ p>
- * <p> Copyright: Copyright (c) 2004 jiahansoft </ p>
- * <p> Company: jiahansoft </ p>
- * @ Author wanghw
- * @ Version 1.0
- * /
- public class UpLoadAction extends Action {
- public ActionForward execute (ActionMapping mapping,
- ActionForm form,
- HttpServletRequest request,
- HttpServletResponse response)
- throws Exception {
- if (form instanceof UpLoadForm) {/ / If the form is UpLoadsForm
- String encoding = request.getCharacterEncoding ();
- if ((encoding! = null) & & (encoding.equalsIgnoreCase ("utf-8")))
- {
- response.setContentType ("text / html; charset = gb2312");
- }
- UpLoadForm theForm = (UpLoadForm) form;
- FormFile file = theForm.getTheFile ();// get the uploaded file
- String contentType = file.getContentType ();
- String size = (file.getFileSize () + "bytes ");// file size
- String fileName = file.getFileName ();// file name
- try {
- InputStream stream = file.getInputStream ();// read the file
- String filePath = request.getRealPath ("/");// get the current system path
- ByteArrayOutputStream baos = new ByteArrayOutputStream ();
- OutputStream bos = new FileOutputStream (filePath + "/" +
- file.getFileName ());
- / / Create an output stream uploaded files will upload the file into the web application's root directory.
- / / System.out.println (filePath +"/"+ file.getFileName ());
- int bytesRead = 0;
- byte [] buffer = new byte [8192];
- while ((bytesRead = stream.read (buffer, 0, 8192))! = -1) {
- bos.write (buffer, 0, bytesRead); / / write a file to the server
- }
- bos.close ();
- stream.close ();
- } Catch (Exception e) {
- System.err.print (e);
- }
- / / Request.setAttribute ("dat", file.getFileName ());
- request.setAttribute ("contentType", contentType);
- request.setAttribute ("size", size);
- request.setAttribute ("fileName", fileName);
- return mapping.findForward ("display");
- }
- return null;
- }
- }
package org.apache.struts.webapp.upload;
import java.io.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
/**
* <p>Title:UpLoadAction</p>
* <p>Description: QRRSMMS </p>
* <p>Copyright: Copyright (c) 2004 jiahansoft</p>
* <p>Company: jiahansoft</p>
* @author wanghw
* @version 1.0
*/
public class UpLoadAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (form instanceof UpLoadForm) {// If the form is UpLoadsForm
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
{
response.setContentType("text/html; charset=gb2312");
}
UpLoadForm theForm = (UpLoadForm ) form;
FormFile file = theForm.getTheFile();// Upload file access
String contentType = file.getContentType();
String size = (file.getFileSize() + " bytes");// File Size
String fileName= file.getFileName();// File Name
try {
InputStream stream = file.getInputStream();// Read the file
String filePath = request.getRealPath("/");// Take the current system path
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/" +
file.getFileName());
// The output of a uploaded file stream into the uploaded file web Application's root directory .
//System.out.println(filePath+"/"+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// Write a file to the server
}
bos.close();
stream.close();
}catch(Exception e){
System.err.print(e);
}
//request.setAttribute("dat",file.getFileName());
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("fileName", fileName);
return mapping.findForward("display");
}
return null;
}
}
Page display.jsp successful
Jsp code
- <% @ Page contentType = "text / html; charset = GBK"%>
- <% @ Page import = "org.apache.struts.action .*,
- java.util.Iterator,
- org.apache.struts.Globals "%>
- <% @ Taglib uri = "/ tags / struts-html" prefix = "html"%>
- Upload successful! From the following information:
- <p>
- <b> The File name: </ b> <% = request.getAttribute ("fileName")%>
- </ P>
- <p>
- <b> The File content type: </ b> <% = request.getAttribute ("contentType")%>
- </ P>
- <p>
- <b> The File size: </ b> <% = request.getAttribute ("size")%>
- </ P>
- <hr />
- <hr />
- <html:link module="/upload" page="/upload.do"> continue to upload </ html: link> </ h2>
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="org.apache.struts.action.*,
java.util.Iterator,
org.apache.struts.Globals" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
Upload successful ! By the following information :
<p>
<b>The File name:</b> <%= request.getAttribute("fileName") %>
</p>
<p>
<b>The File content type:</b> <%= request.getAttribute("contentType") %>
</p>
<p>
<b>The File size:</b> <%= request.getAttribute("size") %>
</p>
<hr />
<hr />
<html:link module="/upload" page="/upload.do"> Continue to upload </html:link></h2>
Sixth, the test from the site and download the whole directory structure TestStruts into tomcat webapps directory, type in the browser:
http://127.0.0.1:8080/TestStruts/upload/upload.do
Original: http://jc-dreaming.javaeye.com/blog/637923
Related Posts of Several common file upload in jsp and struts Methods
-
Struts2 Spring Hibernate's easy to integrate
1. Add Spring 2.0 in Libraries Choose the following four jar, and configure the / WEB-INF/lib under Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries At the same time, the applicationContext ...
-
Hibernate Inteceptor
The end of the project stage, the client suddenly put forward a very troublesome but normal demand, the system records all changes must be carried out. Formats such as: 2004.1.1 12:30 Ikuya wind orders Sales Order Date 2004.1.2-> 2004.1.3 The firs ...
-
jboss ejb3 Message Driven Bean
Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri
-
RoR explained
ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th
-
FLEX: integrating Spring + Hibernate
Before a friend also wanted to study development of FLEX. Asked me to help him to be a small sample. Spent a weekend time, to integrate a sampleproject. Client: FLEX Server: Spring2.5 + Hibernate3.2 + Hibernate-annotations3.3.1 + MySQL5 FDS: BlazeDS3 IDE:
-
Process migration from tomcat to websphere changes
Process migration from tomcat to websphere changes Because customers use the web application server software used by different what tomcat5, tomcat6, websphere5.1, websphere6.1, weblogic8, and so on, and the software used inconsistent standards, ibm's
-
myeclipse plugin
myeclipsePlug-ins? 1.tomcatPlugin(Start tomcat ):http ://www.sysdeo.com/eclipse/tomcatPlugin.html,2.xVersions of eclipse 3 version 2 .1Version doesn't work. 2.Lomboz(Development of jsp program ,jspDynamic prompt, debugging ):http://forge.objectweb.org/pro
-
hibernate generic generic DAO
package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *
-
Servlet brief introduction
Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...
-
The level Hibernate cache
Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...












