How to upload files on a web page

Source: Internet
Author: User
How to upload files on a web page
Public class uploadservlet extends httpservlet
{
// Default maximum allowable file size is 100 K
Static final int max_size = 102400;
// Instance variables to store root and success message
String rootpath, successmessage;
/**
* Init method is called when servlet is initialized.
*/
Public void Init (servletconfig config) throws servletexception
{
Super. INIT (config );
// Get path in which to save file
Rootpath = config. getinitparameter (rootpath );
If (rootpath = NULL)
{
Rootpath = /;
}
/* Get message to show when upload is complete. used only if
A success redirect page is not supplied .*/
Successmessage = config. getinitparameter (successmessage );
If (successmessage = NULL)
{
Successmessage = File Upload complete !;
}
}
/**
* Dopost reads the uploaded data from the request and writes
* It to a file.
*/
Public void dopost (httpservletrequest request,
Httpservletresponse response)
{
Servletoutputstream out = NULL;
Datainputstream in = NULL;
Fileoutputstream fileout = NULL;
Try
{
/* Set content type of response and get handle to output
Stream in case we are unable to redirect client */
Response. setcontenttype (text/plain );
Out = response. getoutputstream ();
}
Catch (ioexception E)
{
// Print error message to standard out
System. Out. println (error getting output stream .);
System. Out. println (error Description: + E );
Return;
}
Try
{
// Get content type of client request
String contenttype = request. getcontenttype ();
// Make sure content type is multipart/form-Data
If (contenttype! = NULL & contenttype. indexof (
Multipart/form-data )! =-1)
{
// Open input stream from client to capture Upload File
In = new datainputstream (request. getinputstream ());
// Get length of content data
Int formdatalength = request. getcontentlength ();
// Allocate a byte array to store content data
Byte databytes [] = new byte [formdatalength];
// Read file into byte array
Int bytesread = 0;
Int totalbytesread = 0;
Int sizecheck = 0;
While (totalbytesread <formdatalength)
{
// Check for maximum file size Violation
Sizecheck = totalbytesread + in. Available ();
If (sizecheck> max_size)
{
Out. println (Sorry, file is too large to upload .);
Return;
}
Bytesread = in. Read (databytes, totalbytesread,
Formdatalength );
Totalbytesread + = bytesread;
}
// Create string from byte array for easy manipulation
String file = new string (databytes );
// Since byte array is stored in string, release memory
Databytes = NULL;
/* Get boundary value (boundary is a unique string that
Separates content data )*/
Int lastindex = contenttype. lastindexof (= );
String boundary = contenttype. substring (lastindex + 1,
Contenttype. Length ());
// Get directory web variable from request
String directory =;
If (file. indexof (name =/directory/)> 0)
{
Directory = file. substring (
File. indexof (name =/directory /));
// Remove carriage return
Directory = directory. substring (
Directory. indexof (/n) + 1 );
// Remove carriage return
Directory = directory. substring (
Directory. indexof (/n) + 1 );
// Get directory
Directory = directory. substring (0,
Directory. indexof (/N)-1 );
/* Make sure user didnt select a directory higher in
The directory tree */
If (directory. indexof (...)> 0)
{
Out. println (security error: You cant upload +
To a directory higher in the directory tree .);
Return;
}
}
// Get successpage web variable from request
String successpage =;
If (file. indexof (name =/successpage/)> 0)
{
Successpage = file. substring (
File. indexof (name =/successpage /));
// Remove carriage return
Successpage = successpage. substring (
Successpage. indexof (/n) + 1 );
// Remove carriage return
Successpage = successpage. substring (
Successpage. indexof (/n) + 1 );
// Get success page
Successpage = successpage. substring (0,
Successpage. indexof (/N)-1 );
}
// Get overwrite flag web variable from request
String overwrite;
If (file. indexof (name =/overwrite/)> 0)
{
Overwrite = file. substring (
File. indexof (name =/overwrite /));
// Remove carriage return
Overwrite = overwrite. substring (
Overwrite. indexof (/n) + 1 );
// Remove carriage return
Overwrite = overwrite. substring (
Overwrite. indexof (/n) + 1 );
// Get overwrite flag
Overwrite = overwrite. substring (0,
Overwrite. indexof (/N)-1 );
}
Else
{
Overwrite = false;
}
// Get overwritepage web variable from request
String overwritepage =;
If (file. indexof (name =/overwritepage/)> 0)
{
Overwritepage = file. substring (
File. indexof (name =/overwritepage /));
// Remove carriage return
Overwritepage = overwritepage. substring (
Overwritepage. indexof (/n) + 1 );
// Remove carriage return
Overwritepage = overwritepage. substring (
Overwritepage. indexof (/n) + 1 );
// Get overwrite page
Overwritepage = overwritepage. substring (0,
Overwritepage. indexof (/N)-1 );
}
// Get filename of Upload File
String SaveFile = file. substring (
File. indexof (filename =/) + 10 );
SaveFile = SaveFile. substring (0,
SaveFile. indexof (/n ));
SaveFile = SaveFile. substring (
SaveFile. lastindexof (//) + 1,
SaveFile. indexof (/));
/* Remove boundary markers and other multipart/form-Data
Tags from beginning of Upload File Section */
Int Pos; // position in Upload File
// Find position of Upload File section of request
Pos = file. indexof (filename = /);
// Find position of content-Disposition line
Pos = file. indexof (/N, POS) + 1;
// Find position of Content-Type line
Pos = file. indexof (/N, POS) + 1;
// Find position of blank line
Pos = file. indexof (/N, POS) + 1;
/* Find the location of the next boundary marker
(Marking the end of the upload file data )*/
Int boundarylocation = file. indexof (boundary, POS)-4;
// Upload File lies between POs and boundarylocation
File = file. substring (Pos, boundarylocation );
// Build the full path of the Upload File
String filename = new string (rootpath + directory +
SaveFile );
// Create File object to check for existence of File
File checkfile = new file (filename );
If (checkfile. exists ())
{
/* File exists, if overwrite flag is off, give
Message and abort */
If (! Overwrite. tolowercase (). Equals (true ))
{
If (overwritepage. Equals ())
{
/* Overwrite HTML page url not supported ed, respond
With generic message */
Out. println (Sorry, file already exists .);
}
Else
{
// Redirect client to overwrite HTML page
Response. sendredirect (overwritepage );
}
Return;
}
}
/* Create File object to check for existence
Directory */
File filedir = new file (rootpath + directory );
If (! Filedir. exists ())
{
// Directory doesnt exist, create it
Filedir. mkdirs ();
}
// Instantiate file output stream
Fileout = new fileoutputstream (filename );
// Write the string to the file as a byte array
Fileout. Write (file. getbytes (), 0, file. Length ());
If (successpage. Equals ())
{
/* Success HTML page url not supported ed, respond
Generic success message */
Out. println (successmessage );
Out. println (file written to: + filename );
}
Else
{
// Redirect client to Success HTML page
Response. sendredirect (successpage );
}
}
Else // request is not multipart/form-Data
{
// Send error message to client
Out. println (request not multipart/form-Data .);
}
}
Catch (exception E)
{
Try
{
// Print error message to standard out
System. Out. println (error in dopost: + E );
// Send error message to client
Out. println (an unexpected error has occurred .);
Out. println (error Description: + E );
}
Catch (exception f ){}
}
Finally
{
Try
{
Fileout. Close (); // close file output stream
}
Catch (exception f ){}
Try
{
In. Close (); // close input stream from client
}
Catch (exception f ){}
Try
{
Out. Close (); // close output stream to client
}
Catch (exception f ){}
}
}
}

 

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.