Apache commons-fileupload implements file upload and download

Source: Internet
Author: User

Package com. handson. bbs. servlet;

 

Import java. Io. file;

Import java. Io. ioexception;

Import java. util. date;

Import java. util. List;

Import javax. servlet. servletexception;

Import javax. servlet. http. httpservlet;

Import javax. servlet. http. httpservletrequest;

Importjavax. servlet. http. httpservletresponse;

Import javax. servlet. http. httpsession;

Importorg. Apache. commons. fileupload. fileitem;

Importorg. Apache. commons. fileupload. disk. diskfileitemfactory;

Importorg. Apache. commons. fileupload. servlet. servletfileupload;

Import com. handson. bbs. Bo. userbo;

Import com. handson. bbs. model. user;

/***//**

**************************************** *******

* @ Description file upload

* For this project, upload images in uploadfile/Image

* Cache directory c: \ TMP \

* After the photo is uploaded, the subsequent code is processed to update the user's photo in a timely manner.

* @ Author Gavin. Lee

* @ Date 2009-6-13 21:35:47

* @ Version 1.0

**************************************** *******

*/

Public class uploadphotoservlet extendshttpservlet {

Public void doget (httpservletrequest request, httpservletresponseresponse)

Throws servletexception, ioexception {

This. dopost (request, response );

}

 

Public void dopost (httpservletrequest request, httpservletresponseresponse)

Throws servletexception, ioexception {

String filepath = This. getservletcontext (). getrealpath ("/uploadfile/image/"); // container relative path

File TMP = new file ("C: \ TMP \\");

If (! TMP. exists ()){

TMP. mkdirs ();

}

Diskfileitemfactory factory = new diskfileitemfactory (); // create a disk Factory

Factory. setrepository (TMP); // File Cache path

Factory. setsizethreshold (1096x10 );

Servletfileupload SFU = new servletfileupload (factory); // create a processing tool

SFU. setsizemax (10*1024*1024); // The maximum file size that the server can receive.-1 indicates no upper limit.

String filename = NULL;

Try {

List <fileitem> List = SFU. parserequest (request); // parse

Fileitem item = list. Get (0 );

Filename = item. getname ();

If (filename. Equals ("")){

Request. getrequestdispatcher ("/COM/visualizephoto. jsp"). Forward (request, response );

Return;

}

Int Pos = filename. lastindexof ("."); // retrieves the image file format

If (Pos> 0 ){

Date = new date ();

Filename = filepath + '/' + date. gettime () + filename. substring (POS );

}

Item. Write (new file (filename); // write to disk

} Catch (exception e ){

E. printstacktrace ();

}

// If the object is uploaded only, you do not need to check the subsequent code. The latter is to update user information (photos) in a timely manner)

Httpsession session = request. getsession ();

User user = (User) Session. getattribute ("user ");

Int Pos = filename. indexof ("uploadfile"); // sets the relative path of the image.

If (Pos> 0 ){

Filename = filename. substring (Pos, POS + 10) + '/' + filename. substring (Pos + 11 );

}

User. setphoto (filename );

Userbo = userbo. getinstance ();

If (userbo. updateuser (User )){

Session. setattribute ("user", user );

Request. getrequestdispatcher ("/COM/visualizephoto. jsp"). Forward (request, response );

}

}

 

}

 

[Download]

Download seems simpler. packagecom. Gavin. Tools. fileupload;

 

Import java. Io. file;

Import java. Io. fileinputstream;

Import java. Io. ioexception;

Import java. Io. inputstream;

Import java. Io. printwriter;

 

Import javax. servlet. servletconfig;

Import javax. servlet. servletexception;

Import javax. servlet. http. httpservlet;

Importjavax. servlet. http. httpservletrequest;

Importjavax. servlet. http. httpservletresponse;

 

Public class filedownloadservlet extendshttpservlet {

 

Public void dopost (httpservletrequest request, httpservletresponseresponse)

Throws servletexception {

String filename = request. getparameter ("file_name ");

If (filename = NULL)

Filename = "";

Filename = filename. Trim ();

 

Inputstream instream = NULL;

String attchname = "";

 

Byte [] B = new byte [100];

Int Len = 0;

Try {

Attchname = getattachname (filename); // get the attachment name

Filename = getrealname (request, filename); // obtain the full path of the Attachment

If (filename = NULL ){

System. Out. println ("the file does not exist or cannot be downloaded ");

Return;

}

Attchname = toutf8string (attchname); // transcode the file UTF-8

Instream = new fileinputstream (filename );

Response. Reset (); // The Reset is required; otherwise, the file is incomplete.

Response. setcontenttype ("application/X-msdownload ");

Response. addheader ("content-disposition", "attachment; filename = \" "+ attchname + "\"");

// Cyclically retrieve the data in the stream

While (LEN = instream. Read (B)> 0 ){

Response. getoutputstream (). Write (B, 0, Len );

}

Instream. Close ();

} Catch (exception e ){

E. printstacktrace ();

}

}

 

// Obtain the attachment name

Public static string getattachname (string filename ){

If (filename = NULL)

Return "";

Filename = filename. Trim ();

Int Pos = 0;

Pos = filename. lastindexof ("\\");

If (Pos>-1 ){

Filename = filename. substring (Pos + 1 );

}

Pos = filename. lastindexof ("/");

If (Pos>-1 ){

Filename = filename. substring (Pos + 1 );

}

Pos = filename. lastindexof (file. separator );

If (Pos>-1 ){

Filename = filename. substring (Pos + 1 );

}

Return filename;

}

 

// Utf8 Transcoding

Public static string toutf8string (string ){

Stringbuffer sb = new stringbuffer ();

For (INT I = 0; I <string. Length (); I ++ ){

Char c = string. charat (I );

If (C> = 0 & C <= 255 ){

SB. append (C );

} Else {

Byte [] B;

Try {

B = character. tostring (c). getbytes ("UTF-8 ");

} Catch (exception ex ){

System. Out. println (Ex );

B = new byte [0];

}

For (Int J = 0; j <B. length; j ++ ){

Int K = B [J];

If (k <0)

K + = 256;

SB. append ("%" + integer. tohexstring (k). touppercase ());

}

}

}

String s_utf8 = sb. tostring ();

SB. Delete (0, SB. Length ());

SB. setlength (0 );

SB = NULL;

Return s_utf8;

}

 

// Obtain the real full path name of the downloaded object

Private string getrealname (httpservletrequest request, string filename ){

If (request = NULL | filename = NULL)

Return NULL;

Filename = filename. Trim ();

If (filename. Equals (""))

Return NULL;

 

String filepath = request. getrealpath (filename );

If (filepath = NULL)

Return NULL;

File file = new file (filepath );

If (! File. exists ())

Return NULL;

Return filepath;

}

 

Public void doget (httpservletrequest request, httpservletresponseresponse)

Throws servletexception {

This. dopost (request, response );

}

 

}

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.