Upload and download Java files

Source: Internet
Author: User

Upload and download Java files

File Upload is very common in Web applications. It is very easy to implement the file upload function in the JSP environment, because there are many File Upload components developed using Java on the Internet, this document uses the commons-fileupload component as an example to add the file upload function for JSP applications.
The common-fileupload component is one of Apache's open-source projects. It can be downloaded from http://jakarta.apache.org/commons/fileupload.
You can use this component to upload one or more files at a time and limit the file size.

Download and decompress the zip package, copy the commons-fileupload-1.0.jar to Tomcat's webapps under your webappweb-inflib, the directory does not exist please self-built directory.
Create a servlet: Upload. Java for file upload:
Import java. Io .*;
Import java. util .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import org. Apache. commons. fileupload .*;

Public class upload extends httpservlet {

Private string uploadpath = "C: Upload"; // directory of the uploaded file
Private string temppath = "C: uploadtmp"; // temporary file directory

Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws ioexception, servletexception
{
}
}
In the dopost () method, when the servlet receives a POST request from the browser, it uploads the file. The following is the sample code:
Public void dopost (httpservletrequest request,
Httpservletresponse response)
Throws ioexception, servletexception
{
Try {
Diskfileupload Fu = new diskfileupload ();
// Set the maximum file size, which is 4 MB
Fu. setsizemax (4194304 );
// Set the buffer size, which is 4 kb
Fu. setsizethreshold (4096 );
// Set the temporary directory:
Fu. setrepositorypath (temppath );

// Obtain all objects:
List fileitems = Fu. parserequest (request );
Iterator I = fileitems. iterator ();
// Process each file in sequence:
While (I. hasnext ()){
Fileitem Fi = (fileitem) I. Next ();
// Get the file name, which includes the path:
String filename = Fi. getname ();
// User and file information can be recorded here
//...
// Write the file. The temporary file name is a.txt. You can extract the file name from filename:
Fi. Write (new file (uploadpath + "a.txt "));
}
}
Catch (exception e ){
// Jump to the error page
}
}
To read the specified upload folder in the configuration file, run the following command in the init () method:
Public void Init () throws servletexception {
Uploadpath = ....
Temppath = ....
// The folder is automatically created if it does not exist:
If (! New file (uploadpath). isdirectory ())
New file (uploadpath). mkdirs ();
If (! New file (temppath). isdirectory ())
New file (temppath). mkdirs ();
}
Compile the servlet, note that you need to specify classpath to ensure that the commons-upload-1.0.jar and tomcatcommonlibservlet-api.jar are included.
Configure servlet, use NotePad to open tomcatwebapps your webappWEB-INFweb.xml, and create a new one if there is no.
The typical configuration is as follows:
<〈? 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> 〉
After configuring the servlet, start Tomcat and write a simple HTML test:
<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 action = "fileupload" where fileupload is the URL-pattern specified When configuring the servlet.

The following is the code for a prawns:

This upload is much easier to use than smartupload. It is completely debugged by byte, unlike many bugs in smartupload.
Call method:
Upload up = new upload ();
Up. INIT (request );
/**
You can call setsavedir (string savedir) to set the storage path.
Call setmaxfilesize (Long SIZE) to set the maximum byte of the uploaded file.
Call settagfilename (string) to set the name of the uploaded file (only valid for the first file)
*/
Up. uploadfile ();

Then string [] names = up. getfilename (); to get the uploaded file name, the absolute path of the file should be
Saved directory savedir + "/" + Names [I];
You can use up. getparameter ("field"); to obtain the uploaded text or up. getparametervalues ("filed ")
Obtain the values of fields with the same name, such as multiple checkboxes.
Try other items by yourself.

Source code :____________________________________________________________
Package com. inmsg. beans;

Import java. Io .*;
Import java. util .*;
Import javax. servlet .*;
Import javax. servlet. http .*;

Public class upload {
Private string savedir = "."; // path of the file to be saved
Private string contenttype = ""; // Document Type
Private string charset = ""; // Character Set
Private arraylist tmpfilename = new arraylist (); // temporary data structure for storing file names
Private hashtable parameter = new hashtable (); // data structure for storing parameter names and values
Private servletcontext context; // The context of the Program for initialization.
Private httpservletrequest request; // instance used to pass in the request object
Private string boundary = ""; // delimiter of Memory Data
Private int Len = 0; // the actual length of the byte read from the inner each time
Private string querystring;
Private int count; // The total number of uploaded files.
Private string [] filename; // array of uploaded file names
Private long maxfilesize = 1024*1024*10; // Maximum File Upload bytes;
Private string tagfilename = "";

Public final void Init (httpservletrequest request) throws servletexception {
This. Request = request;
Boundary = request. getcontenttype (). substring (30); // obtain the data delimiter in the memory.
Querystring = request. getquerystring ();
}

Public String getparameter (string s) {// used to obtain the parameter value of the specified field, override request. getparameter (string S)
If (parameter. isempty ()){
Return NULL;
}
Return (string) parameter. Get (s );
}

Public String [] getparametervalues (string s) {// used to obtain the parameter array of the specified field with the same name, override request. getparametervalues (string S)
Arraylist Al = new arraylist ();
If (parameter. isempty ()){
Return NULL;
}
Enumeration E = parameter. Keys ();
While (E. hasmoreelements ()){
String key = (string) E. nextelement ();
If (-1! = Key. indexof (S + "|") | key. Equals (s )){
Al. Add (parameter. Get (key ));
}
}
If (Al. Size () = 0 ){
Return NULL;
}
String [] value = new string [Al. Size ()];
For (INT I = 0; I <value. length; I ++ ){
Value [I] = (string) Al. Get (I );
}
Return value;
}

Public String getquerystring (){
Return querystring;
}

Public int getcount (){
Return count;
}

Public String [] getfilename (){
Return filename;
}

Public void setmaxfilesize (Long SIZE ){
Maxfilesize = size;
}

Public void settagfilename (string filename ){
Tagfilename = filename;
}

Public void setsavedir (string savedir) {// set the path to save the uploaded file
This. savedir = savedir;
File testdir = new file (savedir); // to ensure that the directory exists, if not, create the Directory
If (! Testdir. exists ()){
Testdir. mkdirs ();
}
}

Public void setcharset (string charset) {// sets the character set
This. charset = charset;
}

Public Boolean uploadfile () throws servletexception, ioexception {// upload method called by the user
Setcharset (request. getcharacterencoding ());
Return uploadfile (request. getinputstream ());
}

Private Boolean uploadfile (servletinputstream) throws // master method for obtaining Central Data
Servletexception, ioexception {
String line = NULL;
Byte [] buffer = new byte [256];
While (line = Readline (buffer, servletinputstream, charset ))! = NULL ){
If (line. startswith ("content-Disposition: Form-data ;")){
Int I = line. indexof ("filename = ");
If (I >= 0) {// if there is filename = In the description of a delimiter, it indicates the encoding of the file.
String fname = getfilename (line );
If (fname. Equals ("")){
Continue;
}
If (COUNT = 0 & tagfilename. Length ()! = 0 ){
String ext = fname. substring (fname. lastindexof (".") + 1 ));
Fname = tagfilename + "." + ext;
}
Tmpfilename. Add (fname );
Count ++;
While (line = Readline (buffer, servletinputstream, charset ))! = NULL ){
If (line. Length () <=2 ){
Break;
}
}
File F = new file (savedir, fname );
Fileoutputstream dos = new fileoutputstream (f );
Long size = 0l;
While (line = Readline (buffer, servletinputstream, null ))! = NULL ){
If (line. indexof (Boundary )! =-1 ){
Break;
}
Size + = Len;
If (size> maxfilesize ){
Throw new ioexception ("file exceeds" + maxfilesize + "bytes! ");
}
Dos. Write (buffer, 0, Len );
}
Dos. Close ();
}
Else {// otherwise it is field-encoded content
String key = getkey (line );
String value = "";
While (line = Readline (buffer, servletinputstream, charset ))! = NULL ){
If (line. Length () <=2 ){
Break;
}
}
While (line = Readline (buffer, servletinputstream, charset ))! = NULL ){

If (line. indexof (Boundary )! =-1 ){
Break;
}
Value + = line;
}
Put (Key, value. Trim (), parameter );
}
}
}
If (querystring! = NULL ){
String [] Each = Split (querystring ,"&");
For (int K = 0; k <each. length; k ++ ){
String [] NV = Split (each [K], "= ");
If (NV. Length = 2 ){
Put (NV [0], NV [1], parameter );
}
}
}
Filename = new string [tmpfilename. Size ()];
For (int K = 0; k <FILENAME. length; k ++ ){
Filename [k] = (string) tmpfilename. Get (k); // Add the temporary file name in arraylist to the data for calling.
}
If (filename. Length = 0 ){
Return false; // If the filename data is null, no file is uploaded.
}
Return true;
}

Private void put (string key, string value, hashtable HT ){
If (! Ht. containskey (key )){
Ht. Put (Key, value );
}
Else {// If a key with the same name already exists, rename the current key.
Try {
Thread. currentthread (). Sleep (1); // to generate two identical keys in different Ms
}
Catch (exception e ){}
Key + = "|" + system. currenttimemillis ();
Ht. Put (Key, value );
}
}

/*
Call the servletinputstream. Readline (byte [] B, int offset, length) method to read a row from the servletinputstream stream.
To the specified byte array, to ensure a row can be accommodated, the byte [] B should not be less than 256. In the rewritten Readline, a member variable Len is called
The actual number of bytes read (some rows are less than 256), The LEN Length bytes should be written from the byte array instead of the entire byte [] during file content writing.
This method returns a string to analyze the actual content, but does not return Len, So Len is set as a member variable, during each read operation
Assign the actual length to it.
That is to say, when processing the file content, the data must be returned in string form for analysis start and end marking, and written to the file in the form of byte [] at the same time.
Output stream.
*/
Private string Readline (byte [] linebyte,
Servletinputstream, string charset ){
Try {
Len = servletinputstream. Readline (linebyte, 0, linebyte. Length );
If (LEN =-1 ){
Return NULL;
}
If (charset = NULL ){
Return new string (linebyte, 0, Len );
}
Else {
Return new string (linebyte, 0, Len, charset );
}

}
Catch (exception _ ex ){
Return NULL;
}

}

Private string getfilename (string line) {// extract the file name from the description string
If (line = NULL ){
Return "";
}
Int I = line. indexof ("filename = ");
Line = line. substring (I + 9). Trim ();
I = line. lastindexof ("");
If (I <0 | I> = line. Length ()-1 ){
I = line. lastindexof ("/");
If (line. Equals ("""")){
Return "";
}
If (I <0 | I> = line. Length ()-1 ){
Return line;
}
}
Return line. substring (I + 1, line. Length ()-1 );
}

Private string getkey (string line) {// extract the field name from the description string
If (line = NULL ){
Return "";
}
Int I = line. indexof ("name = ");
Line = line. substring (I + 5). Trim ();
Return line. substring (1, line. Length ()-1 );
}

Public static string [] Split (string strob, string mark ){
If (strob = NULL ){
Return NULL;
}
Stringtokenizer ST = new stringtokenizer (strob, mark );
Arraylist TMP = new arraylist ();
While (St. hasmoretokens ()){
TMP. Add (St. nexttoken ());
}
String [] strarr = new string [TMP. Size ()];
For (INT I = 0; I <TMP. Size (); I ++ ){
Strarr [I] = (string) TMP. Get (I );
}
Return strarr;
}
}
Download is actually very simple, as long as the following processing, there will be no problem.

Public void download (string filepath, httpservletresponse response, Boolean isonline)
Throws exception {
File F = new file (filepath );
If (! F. exists ()){
Response. senderror (404, "file not found! ");
Return;
}
Bufferedinputstream BR = new bufferedinputstream (New fileinputstream (f ));
Byte [] Buf = new byte [1, 1024];
Int Len = 0;

Response. Reset (); // very important
If (isonline) {// online open mode
URL u = new URL ("file: //" + filepath );
Response. setcontenttype (U. openconnection (). getcontenttype ());
Response. setheader ("content-disposition", "inline; filename =" + F. getname ());
// The file name should be encoded into a UTF-8
}
Else {// download method only
Response. setcontenttype ("application/X-msdownload ");
Response. setheader ("content-disposition", "attachment; filename =" + F. getname ());
}
Outputstream out = response. getoutputstream ();
While (LEN = Br. Read (BUF)> 0)
Out. Write (BUF, 0, Len );
BR. Close ();
Out. Close ();
}

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.