Two Methods for uploading files using JSP

Source: Internet
Author: User

Previously, cos was used for file upload. However, other tools are required for renaming the uploaded file.

The excerpt is as follows:


When Java is used to develop the enterprise system, especially for office-related software development, file upload is a frequently-mentioned requirement. therefore, there is a set of good File Upload solutions that can facilitate your development in this area.

First of all, I declare that this article is intended to record the development requirements after preparation, so you don't have to worry about it ........

Currently, there are many methods used in China to solve the problem of file upload.

Cos. jar + uploadbean. jar + filemover. jar
This is widely used because it is easy to operate and we don't have to pay attention to it anymore. The input and output streams of those files free us from the underlying streams.
UploadFile, UploadBean, MultipartFormDataRequest

<% @ Page contentType = "text/html; charset = gb2312" %>
<Head>
<Title> fbysss UploadBean example </title>
<! -- Meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1" -->
<! -- Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312" -->
</Head>
<FORM name = "form1" METHOD = "POST" ACTION = "sssupload. jsp" ENCTYPE = "multipart/form-data">
<Input name = "title" type = "text" value = "Chinese text">
<Td class = "bodystyle"> attachment </td>
<Td class = "bodystyle"> <input name = "attach" type = "FILE" id = "attach" size = "50"> </td>
<Input name = "OK" type = "submit" value = "submit">
</Form>

2. Read the form page sssgetdata. jsp

<! --
// ================================================ ==========================================
// File: UploadBean upload instance
// Function: solves Chinese garbled characters, completes file upload, and provides a RENAME upload Solution
// By fbysss
// Msn: jameslastchina@hotmail.com
// ================================================ ==========================================
-->
<% @ Page contentType = "text/html; charset = GBK" %>
<% @ Page language = "java" import = "com. jspsmart. upload. *" %>
<% @ Page import = "java. text. SimpleDateFormat" %>
<% @ Page import = "java. io. File" %>
<% @ Page import = "java. util. *" %>
<% @ Page import = "javazoom. upload. *" %>
<% @ Page import = "uploadutilities. FileMover" %>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>
<%
Request. setCharacterEncoding ("GBK"); // you do not need to transcode each time you set the encoding format.
FileMover fileMover = new FileMover (); // You can also use the form of jsp: useBean in your own instance.
UploadBean upBean = new UploadBean ();
MultipartFormDataRequest mrequest = null;
Hashtable files = null;

If (MultipartFormDataRequest. isMultipartFormData (request ))
{
Mrequest = new MultipartFormDataRequest (request, null, 100*1024*1024, MultipartFormDataRequest. COSPARSER, "GBK"); // you must set the encoding parameters here.
String sTt0 = mrequest. getParameter ("title ");
Out. println ("<br> Title0 is:" + sTt0 + "<br> ");
String sTt1 = new String (sTt0.getBytes ("ISO-8859-1"), "GBK ");
Out. println ("<br> Title1 is:" + sTt1 + "<br> ");
// Check whether the title parameter is correct. When debugging, add if (true) return.
Files = mrequest. getFiles ();
}


// Get the file name before modification
String sOldFileName = mrequest. getParameter ("oldfilename ");
Out. println ("sOldFileName:" + sOldFileName );
String sWebRootPath = request. getRealPath ("/"); // obtain the root of your web application.
String sPath = sWebRootPath + "attach ";
Int iFileCount = 0;
String sServerFileName = "";
String sLocalFileName = "";
// File Retrieval
If (files! = Null) | (! Files. isEmpty ())){

IFileCount = files. size ();
UploadFile file = (UploadFile) files. get ("attach ");
SLocalFileName = file. getFileName ();
Out. println ("sLocalFileName:" + sLocalFileName );
Int ii = sLocalFileName. indexOf ("."); // get the filename suffix
String sExt = sLocalFileName. substring (ii, sLocalFileName. length ());
// Get non-repeated file names
Java. util. Date dt = new java. util. Date (System. currentTimeMillis ());
SimpleDateFormat fmt = new SimpleDateFormat ("yyyyMMddHHmmssSSS ");
SServerFileName = fmt. format (dt );
SServerFileName = sServerFileName + sExt;
// If this directory does not exist, create
File dir = new File (sPath );
If (! Dir. exists ()){
Dir. mkdirs ();
}
UpBean. setFolderstore (sPath); // you can specify the directory to be uploaded.
UpBean. addUploadListener (fileMover); // added the filMover listener.
FileMover. setNewfilename (sServerFileName); // set the file name on the server
UpBean. store (mrequest, "attach"); // upload
Out. println ("file path is" + sPath + "/" + sServerFileName );
}

%>


Demo Note: cos. jar, uploadbean. jar, and filemover. jar must be included.
Required:
UploadBean1.5: http://wcarchive.cdrom.com/pub/simtelnet/winnt/java/uploadbean1_5.zip
FileMover1.3: http://www.javazoom.net/jzservlets/uploadbean/addons/filemover1.3.zip
Refer:
Example of ChinesUpload: http://www.javazoom.net/jzservlets/uploadbean/addons/ChineseUpload.zip
Refer to an article in fbysss
2. org. apache. struts. upload. FormFile
The org. apache. struts. upload. FormFile class of Struts1.1. It is very convenient and you do not need to write it yourself. You do not need to write a jsp to call jspsmartupload.


Select the Upload File page: selfile. jsp


--------------------------------------------------------------------------------
<% @ Taglib uri = "/WEB-INF/struts-html.tld" prefix = "html" %>
<Html: html>
<Html: form action = "/uploadsAction. do" enctype = "multipart/form-data">
<Html: file property = "theFile"/>
<Html: submit/>
</Html: form>
</Html: html>

--------------------------------------------------------------------------------
UpLoadAction. java
--------------------------------------------------------------------------------
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 uploadsForm) {// if form is uploadsForm
String encoding = request. getCharacterEncoding ();
If (encoding! = Null) & (encoding. equalsIgnoreCase ("UTF-8 ")))
{
Response. setContentType ("text/html; charset = gb2312"); // if no encoding is specified, the encoding format is gb2312.
}
UpLoadForm theForm = (UpLoadForm) form;
FormFile file = theForm. getTheFile (); // get the uploaded file
Try {
InputStream stream = file. getInputStream (); // read the file
String filePath = request. getRealPath ("/"); // obtain the current system path
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
OutputStream bos = new FileOutputStream (filePath + "/" +
File. getFileName (); // creates an output stream for the uploaded file.
// 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 the file to the server
}
Bos. close ();
Stream. close ();
} Catch (Exception e ){
System. err. print (e );
}
// Request. setAttribute ("dat", file. getFileName ());
Return mapping. findForward ("display ");
}
Return null;
}
}


--------------------------------------------------------------------------------

UpLoadForm. java

--------------------------------------------------------------------------------


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 (ERROR_PROPERTY_MAX_LENGTH_EXCEEDED, new ActionError ("maxLengthExceeded "));
}
Return errors;

}
}
// This is the corresponding form, and other attributes can be set. For details, refer to the upload example of struts.

--------------------------------------------------------------------------------

Struts-config.xml

--------------------------------------------------------------------------------

<? 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>
<Form-beans>
<Form-bean name = "uploadsForm" type = "UpLoadForm"/>
</Form-beans>
<Action-mappings>
<Action name = "uploadsForm" type = "UpLoadAction" path = "/uploadsAction">
<Forward name = "display" path = "/display. jsp"/>
</Action>
</Action-mappings>
</Struts-config>
<! -- Display. jsp is to write a successful page at will -->

Source: CSDN

Related Article

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.