Commons-fileupload-1.2.1 for File Upload

Source: Internet
Author: User

Many File Upload components are implemented in Java, such as jspsmartupload and commons-fileupload, but jspsmartupload is almost eliminated.
I found the usage related to Apache commons-fileupload on the Internet and called the program, which will be used directly later ..
Jar package used: (download it from www.apache.org)
Commons-fileupload-1.2.1.jar
Commons-io-1.4.jar
There are more detailed usage on the Internet:
Http://www.cnblogs.com/yyw84/archive/2007/06/27/797652.html
Because there are too many codes, you can refer to them if you are interested.

This is the simple code that I used on my machine. Put it below:
Web. xml <? XML version = "1.0" encoding = "UTF-8"?>
<Web-app version = "2.5"
Xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd>
<Servlet>
<Servlet-Name> fileupload </servlet-Name>
<Servlet-class> fileupload. fileuploadservlet </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> fileupload </servlet-Name>
<URL-pattern>/servlet/fileuploadservlet </url-pattern>
</Servlet-mapping>

<Welcome-file-List>
<Welcome-File> fileupload. jsp </welcome-File>
</Welcome-file-List>
</Web-app>

Fileupload. javapackage fileupload;
Import java. Io. file;
Import java. Io. ioexception;
Import java. Io. printwriter;
Import java. util. iterator;
Import java. util. List;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import org. Apache. commons. fileupload. fileitem;
Import org. Apache. commons. fileupload. fileuploadexception;
Import org. Apache. commons. fileupload. fileuploadbase. sizelimitexceededexception;
Import org. Apache. commons. fileupload. disk. diskfileitemfactory;
Import org. Apache. commons. fileupload. servlet. servletfileupload;
Public class fileuploadservlet extends httpservlet {
Public fileuploadservlet (){
Super ();
}
Public void destroy (){
Super. Destroy (); // just puts "Destroy" string in log
// Put your code here
}
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Dopost (request, response );
}
Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Final string apprealpath = This. getservletcontext (). getrealpath ("/"); // obtain the physical path of the web app
Final long max_size = 3*1024*1024; // sets the maximum size of the uploaded file to 3 MB.
Final string [] allowedext = new string [] {"jpg", "Jpeg", "GIF", "TXT ",
"Doc", "docx", "MP3", "WMA", "m4a"}; // list of file formats that can be uploaded
Response. setcontenttype ("text/html ");
Response. setcharacterencoding ("UTF-8"); // set the character encoding to a UTF-8, which supports Chinese Character Display
// Instantiate a hard disk file factory to configure the Upload Component servletfileupload
Diskfileitemfactory dfif = new diskfileitemfactory ();
Dfif. setsizethreshold (4096); // set the memory size used to temporarily store files during file upload. Here, more than 4 kb will be temporarily stored on the hard disk.
Dfif. setrepository (new file (apprealpath + "imagesuploadtemp //"));
// Set the directory for storing temporary files, and the imagesuploadtemp directory under the web root directory
// Use the above factory to instantiate the Upload Component
Servletfileupload SFU = new servletfileupload (dfif );

SFU. setsizemax (max_size); // sets the maximum upload size.
Printwriter out = response. getwriter ();

// Obtain the list of all upload domains from the request
List filelist = NULL;
Try {
Filelist = SFU. parserequest (request );
} Catch (fileuploadexception e) {// handle an exception when the file size is too large
If (E instanceof sizelimitexceededexception ){
Out. println ("the file size exceeds the specified size:" + max_size + "bytes <p/> ");
Out. println ("<a href =/" "+ request. getcontextpath () + "/fileupload. JSP "+"/"target =/" _ top/"> return </a> ");
Return;
}
E. printstacktrace ();
}
// No file is uploaded
If (filelist = NULL | filelist. Size () = 0 ){
Out. println ("Select Upload File <p/> ");
Out. println ("<a href =/" "+ request. getcontextpath () + "/fileupload. JSP "+"/"target =/" _ top/"> return </a> ");
Return;
}
// Obtain all uploaded files
Iterator fileitr = filelist. iterator ();
// Process all objects cyclically
While (fileitr. hasnext ()){
Fileitem = NULL;
String Path = NULL;
Long size = 0;
// Obtain the current file
Fileitem = (fileitem) fileitr. Next ();
// Ignore the simple form field rather than the file field of the uploaded domain (<input type = "text"/>)
If (fileitem = NULL | fileitem. isformfield ()){
Continue;
}
// Obtain the complete file path
Path = fileitem. getname ();
// Get the file size
Size = fileitem. getsize ();
If ("". Equals (PATH) | size = 0 ){
Out. println ("Select Upload File <p/> ");
Out. println ("<a href =/" "+ request. getcontextpath () + "/fileupload. JSP "+"/"target =/" _ top/"> return </a> ");
Return;
}
// Get the name of the removed path
String t_name = path. substring (path. lastindexof ("//") + 1 );
// Get the file extension (the full name will be obtained if there is no extension)
String t_ext = t_name.substring (t_name.lastindexof (".") + 1 );
// Refuse to accept file types other than the specified file format
Int allowflag = 0;
Int allowedextcount = allowedext. length;
For (; allowflag <allowedextcount; allowflag ++ ){
If (allowedext [allowflag]. Equals (t_ext ))
Break;
}
If (allowflag = allowedextcount ){
Out. println ("please upload the following types of files <p/> ");
For (allowflag = 0; allowflag <allowedextcount; allowflag ++)
Out. println ("*." + allowedext [allowflag]
+ "& Nbsp ;");
Out
. Println ("<a href =/" "+ request. getcontextpath () + "/fileupload. JSP "+"/"target =/" _ top/"> return </a> ");
Return;
}
Long Now = system. currenttimemillis ();
// Generate the uploaded file name based on the system time.
String prefix = string. valueof (now );
// Complete path of the stored final file, saved in the imagesuploaded directory under the web root directory
String u_name = apprealpath + "imagesuploaded //"
+ Prefix + "." + t_ext;
Try {
// Save the file
Fileitem. Write (new file (u_name ));
Out. println ("File Uploaded successfully. Saved as:" + prefix + "." + t_ext
+ "& Nbsp; file size:" + size + "bytes <p/> ");
Out. println ("<a href =/" "+ request. getcontextpath () + "/fileupload. JSP "+"/"target =/" _ top/"> continue upload </a> ");
} Catch (exception e ){
E. printstacktrace ();
}
}
}
Public void Init () throws servletexception {
// Put your code here
}
}

Fileupload. jsp <% @ page Language = "Java" Import = "Java. util. *" pageencoding = "gb18030" %>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> my JSP 'fileupload. jsp 'starting page </title>
</Head>

<Body>
<Form action = "<% = request. getcontextpath () %>/servlet/fileuploadservlet" method = "Post" enctype = "multipart/form-Data">
<Input type = "file" name = "fileupload"/>
<Input type = "Submit" value = "Upload"/>
</Form>
</Body>
</Html>

Remember to specify enctype = "multipart/form-Data" in the uploaded form. Read fileupload. Java for details.

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.