JSP page implementation file upload and download class code page 1/2

Source: Internet
Author: User

After watching the movie with LP, I adjusted the JSP page class. Recently, it has always been classic, and I feel like I should leave something for me. LP has been joking and angry over the past few days. As soon as it comes back, it will post a post. You can simply marry the classic LP. Think about it. It may seem a little exaggerated over the past few days, but it will slow down in the future. Keep one week and one week, so you can think about writing more.
The original intention of posting is sometimes to see some friends ask questions, and it seems that they have not yet entered the Java door. I hope such a post will be helpful to new users. Sometimes a casual passage is actually a bit of experience, and sometimes the reason is to clearly understand the problem and make the experts laugh. During the course of getting started, every small step may be depressed for half a day. If I see some of my words, it will be helpful, even if I say one sentence in ten words, I am also satisfied. Because I keep talking.

Now, the summary JSP page upload class is published.CodeThere will certainly be problems. If there is a bug, let me know and I will fix it in time.

Name: JSP page upload class
Author: Sinner
Mail: Vogoals [at] hotmail.com

Features:

    1. Multiple files can be uploaded;
    2. Returns the uploaded file name;
    3. Other parameters in the form can also be obtained.

Post upload class first, jspfileupload

Package com. vogoal. util;
Import java. Io. bufferedoutputstream;
Import java. Io. file;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Text. simpledateformat;
Import java. util. arraylist;
Import java. util. date;
Import java. util. hashtable;
Import javax. servlet. servletinputstream;
Import javax. servlet. http. httpservletrequest;
/*
* Vogoalapis 1.0
* Auther SinNeR@blueidea.com
* By vogoal.com
* Mail: vogoals@hotmail.com
*/
/**
* JSP File Upload
*
* @ Author sinner
* @ Version 1.0
*/
Public class jspfileupload {
/** Request object */
Private httpservletrequest request = NULL;
/** Upload File Path */
Private string uploadpath = NULL;
/** Get the size of the byte for each read */
Private Static int bufsize = 1024*8;
/** Hashtable */
Private hashtable paramht = new hasptable ();
/** Arraylist */
Private arraylist updfilearr = new arraylist ();
/**
* Set the request object.
*
* @ Param request
* Httpservletrequest request object
*/
Public void setrequest (httpservletrequest request ){
This. Request = request;
}
/**
* Set the File Upload path.
*
* @ Param path
* File Upload path specified by the user.
*/
Public void setuploadpath (string path ){
This. uploadpath = path;
}
/**
* File Upload Handler Program . ���� B
*
* @ Return int operation result 0 file operation succeeded; 1 request object does not exist. 2. The file storage path is not set or the file storage path is incorrect. 3.
* An error occurred while setting the correct enctype; 4.
*/
Public int process (){
Int status = 0;
// Check the request object, upload path, and enctype before uploading the file.
Status = precheck ();
// Return the error code when an error occurs.
If (status! = 0)
Return status;
Try {
// The parameter or file name.
String name = NULL;
// Parameter value
String value = NULL;
// Whether the read stream is the object flag
Boolean fileflag = false;
// The file to be stored.
File tmpfile = NULL;
// Name of the uploaded file
String fname = NULL;
Fileoutputstream baos = NULL;
Bufferedoutputstream Bos = NULL;
// �� Hashtable for storing Parameters
Paramht = new hashtable ();
Updfilearr = new arraylist ();
Int rtnpos = 0;
Byte [] buffs = new byte [bufsize * 8];
// Obtain contenttype
String contenttype = request. getcontenttype ();
Int Index = contenttype. indexof ("boundary = ");
String boundary = "--" + contenttype. substring (index + 9 );
String endboundary = boundary + "--";
// Retrieves a stream from the request object.
Servletinputstream SIS = request. getinputstream ();
// Read 1 line
While (rtnpos = sis. Readline (buffs, 0, buffs. Length ))! =-1 ){
String strbuff = new string (buffs, 0, rtnpos );
// Read 1 row of data.
If (strbuff. startswith (Boundary )){
If (name! = NULL & name. Trim (). Length ()> 0 ){
If (fileflag ){
Bos. Flush ();
Baos. Close ();
Bos. Close ();
Baos = NULL;
Bos = NULL;
Updfilearr. Add (fname );
} Else {
Object OBJ = paramht. Get (name );
Arraylist Al = new arraylist ();
If (OBJ! = NULL ){
Al = (arraylist) OBJ;
}
Al. Add (value );
System. Out. println (value );
Paramht. Put (name, Al );
}
}
Name = new string ();
Value = new string ();
Fileflag = false;
Fname = new string ();
Rtnpos = sis. Readline (buffs, 0, buffs. Length );
If (rtnpos! =-1 ){
Strbuff = new string (buffs, 0, rtnpos );
If (strbuff. tolowercase (). startswith (
"Content-Disposition: Form-data ;")){
Int nindex = strbuff. tolowercase (). indexof (
"Name = \"");
Int nlastindex = strbuff. tolowercase (). indexof (
"\" ", Nindex + 6 );
Name = strbuff. substring (nindex + 6, nlastindex );
}
Int findex = strbuff. tolowercase (). indexof (
"Filename = \"");
If (findex! =-1 ){
Fileflag = true;
Int flastindex = strbuff. tolowercase (). indexof (
"\" ", Findex + 10 );
Fname = strbuff. substring (findex + 10, flastindex );
Fname = getfilename (fname );
If (fname = NULL | fname. Trim (). Length () = 0 ){
Fileflag = false;
Sis. Readline (buffs, 0, buffs. Length );
Sis. Readline (buffs, 0, buffs. Length );
Sis. Readline (buffs, 0, buffs. Length );
Continue;
} Else {
Fname = getfilenamebytime (fname );
Sis. Readline (buffs, 0, buffs. Length );
Sis. Readline (buffs, 0, buffs. Length );
}
}
}
} Else if (strbuff. startswith (endboundary )){
If (name! = NULL & name. Trim (). Length ()> 0 ){
If (fileflag ){
Bos. Flush ();
Baos. Close ();
Bos. Close ();
Baos = NULL;
Bos = NULL;
Updfilearr. Add (fname );
} Else {
Object OBJ = paramht. Get (name );
Arraylist Al = new arraylist ();
If (OBJ! = NULL ){
Al = (arraylist) OBJ;
}
Al. Add (value );
Paramht. Put (name, Al );
}
}
} Else {
If (fileflag ){
If (baos = NULL & Bos = NULL ){
Tmpfile = new file (uploadpath + fname );
Baos = new fileoutputstream (tmpfile );
Bos = new bufferedoutputstream (baos );
}
Bos. Write (buffs, 0, rtnpos );
Baos. Flush ();
} Else {
System. Out. println ("test:" + value + "--" + strbuff );
Value = value + strbuff;
}
}
}
} Catch (ioexception e ){
Status = 4;
}
Return status;
}
Private int precheck (){
Int errcode = 0;
If (request = NULL)
Return 1;
If (uploadpath = NULL | uploadpath. Trim (). Length () = 0)
Return 2;
Else {
File tmpf = new file (uploadpath );
If (! Tmpf. exists ())
Return 2;
}
String contenttype = request. getcontenttype ();
If (contenttype. indexof ("multipart/form-Data") =-1)
Return 3;
Return errcode;
}
Public String getparameter (string name ){
String value = "";
If (name = NULL | Name. Trim (). Length () = 0)
Return value;
Value = (paramht. Get (name) = NULL )? "" :( String) (arraylist) paramht. Get (name). Get (0 );
Return value;
}
Public String [] getparameters (string name ){
If (name = NULL | Name. Trim (). Length () = 0)
Return NULL;
If (paramht. Get (name) = NULL)
Return NULL;
Arraylist Al = (arraylist) paramht. Get (name );
String [] strarr = new string [Al. Size ()];
For (INT I = 0; I <Al. Size (); I ++)
Strarr [I] = (string) Al. Get (I );
Return strarr;
}

Public int getupdfilesize (){
Return updfilearr. Size ();
}

Public String [] getupdfilenames (){
String [] strarr = new string [updfilearr. Size ()];
For (INT I = 0; I <updfilearr. Size (); I ++)
Strarr [I] = (string) updfilearr. Get (I );
Return strarr;
}
Private string getfilename (string input ){
Int findex = input. lastindexof ("\\");
If (findex =-1 ){
Findex = input. lastindexof ("/");
If (findex =-1 ){
Return input;
}
}
Input = input. substring (findex + 1 );
Return input;
}
Private string getfilenamebytime (string input ){
Int Index = input. indexof (".");
Date dt = new date ();
Simpledateformat SDF = new simpledateformat ("yyyymmddhhmmsssss ");
Return input. substring (0, index) + SDF. Format (DT) + input. substring (INDEX );
}
}

Description:

This class basically solves the bugs and deficiencies mentioned in the previous post. The following amendments are made.

    1. You can set the File Upload path. Here, the relative path is not obtained using the getrealpath method of the request object, but the absolute path is used. Is a small failure. Sometimes the user only obtains an application of the server and does not know the path of the server. However, since getrealpath can be obtained by yourself, you can also obtain it by yourself.
    2. During file upload, check in advance to check possible upload failures. Avoid exceptions of this class.
    3. I/O exceptions are captured to avoid program unfriendly performance when an exception occurs during file upload.
    4. Provides methods to return the acquisition of other parameters in the Form, and simulates the getparameter and getparameters methods of the httpservletrequest object. (is this name followed by-_-B ), the method for obtaining the parameter name is not provided and is a small defect.
    5. Provides methods to return the number of uploaded files and the file name to facilitate other operations.

This section describes how to use this class to upload files on the JSP page.

First, copy the compiled class file to the WEB-INF/classes/directory. Ensure that the structure of the package is maintained.

Reference this class on the JSP page

<% @ Page import = "com. vogoal. util. jspfileupload" %>

<%
// Initialization
Jspfileupload jfu = new jspfileupload ();
// Set the request object
Jfu. setrequest (request );
// Set the path of the uploaded file
Jfu. setuploadpath ("C :\\");
// Upload Processing
Int RTN = jfu. Process ();
// Obtain the values of other input control parameters in form.
String username = jfu. getparameter ("username ");
// If the same parameter has multiple input controls, an array is returned.
String [] usernamearr = jfu. getparameters ("username ");
// Obtain the name of the uploaded object
String [] filearr = jfu. getupdfilenames ();
// Obtain the number of uploaded files.
Int filenumber = jfu. getupdfilesize ();
// The following is the output code.
// Out. println ("parameter:" + username );
// Out. println ("parameter size:" + usernamearr. Length );
// Out. println ("filearr size:" + filearr. Length );
// If (filearr. length> 0)
// Out. println ("filearr 0:" + filearr [0]);
%>

Precautions for use:

    1. You must set the request object.
    2. Make sure to set the correct upload path.
    3. Other parameters can be obtained after execution, because these parameters are analyzed after execution.

If the process fails to be implemented at, an error is reported during the execution of the process method.

Available methods and descriptions for each user:

Set the requet object.
Public void setrequest (httpservletrequest request)

Set the File Upload path.
Public void setuploadpath (string path)

The main program for file upload processing.
@ Return int operation result 0 file operation succeeded; 1 request object does not exist. 2. The file storage path is not set or the file storage path is incorrect. 3.
An error occurred while setting the correct enctype; 4 file.
Public int process ()

Obtain the value of other passed parameters in the Form Based on name (if there are multiple parameters, one of them is returned)
Public String getparameter (string name)

Obtain the value of other parameters passed in Form Based on name (multiple parameters can be returned)
Public String [] getparameters (string name)

Obtain the number of successfully uploaded files
Public int getupdfilesize ()

Obtains the array corresponding to the uploaded file name.
Public String [] getupdfilenames ()

Note that the return value of the process method fails if it is not 0.

The following are the test classes and test pages.(See the attachment ):

Hellopostfile.html
Hellopostfile. jsp
Test file of the code written in JSP.
Hellopostfilewithclass.html
Hellopostfilewithclass. jsp
Extract the test file after the class.
Src in
WEB-INF/src/
Class in
WEB-INF/classes/

In addition:
I have edited this file in the Chinese-Japanese system and garbled comments, so most of them have been deleted. Sorry.

Download: WEB-INF.zip

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.