Java Upload file

Source: Internet
Author: User

Two jar packages required

Commons-fileupload-1.2.2.jar and Commons-io-2.4.jar

The form format must be

<form action= "fileupload.jsp" method= "post" enctype= "Multipart/form-data" >

An example of accepting a file

<% @pageImport= "Java.io.File"%><% @pageImport= "Org.apache.commons.fileupload.FileItem"%><% @pageImport= "Org.apache.commons.fileupload.servlet.ServletFileUpload"%><% @pageImport= "org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@ page language= "Java"Import= "java.util.*" pageencoding= "Utf-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >request.setcharacterencoding ("Utf-8"); String Uploadpath= "D:/upload"; //file Folder=new file ("Upload");Diskfileitemfactory factory=Newdiskfileitemfactory (); Factory.setsizethreshold (30*1024);        Factory.setrepository (Factory.getrepository ()); Servletfileupload Upload=Newservletfileupload (Factory); intmaxsize=5*1024*1024; List List=upload.parserequest (Request); Iterator Iterator=List.iterator ();  while(Iterator.hasnext ()) {Fileitem Item=(Fileitem) iterator.next (); if(!Item.isformfield ()) {String FilePath=Item.getname (); if(filepath!=NULL) {File filename=NewFile (Item.getname ()); }                if(Item.getsize () >maxsize) {Out.print ("The file is too large to be more than 5M");  Break; } File saveFile=NewFile (Uploadpath,filepath);                Item.write (SaveFile); Out.print ("File Upload succeeded"); } response.sendredirect ("Success.jsp"); }             %> </body>

Prohibit uploading of files of the specified type:

<% @pageImport= "Org.apache.commons.io.filefilter.SuffixFileFilter"%><% @pageImport= "Java.io.File"%><% @pageImport= "Org.apache.commons.fileupload.FileItem"%><% @pageImport= "Org.apache.commons.fileupload.servlet.ServletFileUpload"%><% @pageImport= "org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@ page language= "Java"Import= "java.util.*" pageencoding= "Utf-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >request.setcharacterencoding ("Utf-8"); String Uploadpath= "D:/upload"; //file Folder=new file ("Upload");Diskfileitemfactory factory=Newdiskfileitemfactory (); Factory.setsizethreshold (30*1024);        Factory.setrepository (Factory.getrepository ()); Servletfileupload Upload=Newservletfileupload (Factory); intmaxsize=5*1024*1024; List List=upload.parserequest (Request); string[] Limit = new string[]{". exe", "Dat"}; Suffixfilefilter filter = new suffixfilefilter (limit); Iterator Iterator=List.iterator ();  while(Iterator.hasnext ()) {Fileitem Item=(Fileitem) iterator.next (); if(!Item.isformfield ()) {String FilePath=Item.getname (); if(filepath!=NULL) {File filename=NewFile (Item.getname ()); }                if(Item.getsize () >maxsize) {Out.print ("The file is too large to be more than 5M");  Break; } File saveFile=NewFile (Uploadpath,filepath); BooleanFlag =filter.accept (SaveFile); if(flag) {Out.print ("Error");  Break; }Else{item.write (saveFile); Out.print ("File Upload succeeded");                            }; } response.sendredirect ("Success.jsp"); }             %> </body>

For property enctype of form forms, the default value application/x-www-form-urlencoded is typically used, which allows the form element values to be obtained through the request object's GetParameter () method. However, the Enctype property of the form is set to Multipart/form-data in the file field, which is not available through the GetParameter () method.

An example is described below

Upload page

<%          new  Date ();           = String.Format ("%TF", now);        %>    <form action= "fileupload.jsp" method= "post" enctype= "Multipart/form-data" >         Select Document < Input type= "file" Name= "File1" size= ">         uploader <input type=" text "name=" name "size=" > "        document name <input type= "text" name= "filenames" size= ">         upload time <input type=" text "name = "UpTime" value= "<%=time%>" >        <input type= "Submit" value= "Submit"/>    </form>

Working with pages

<%String name=NULL, filenames=NULL, uptime=NULL, meg=NULL; Request.setcharacterencoding ("Utf-8"); String Uploadpath= "D:/upload"; Diskfileitemfactory Factory=Newdiskfileitemfactory (); Factory.setsizethreshold (30*1024);        Factory.setrepository (Factory.getrepository ()); Servletfileupload Upload=Newservletfileupload (Factory); intMaxSize = 5*1024*1024; List List=upload.parserequest (Request); Iterator Iterator=List.iterator ();  while(Iterator.hasnext ()) {Fileitem Item=(Fileitem) iterator.next (); if(!Item.isformfield ()) {String FilePath=Item.getname (); if(filepath!=NULL) {File filename=NewFile (Item.getname ()); }                if(Item.getsize () >maxsize) {Meg= "Too Big";  Break; } File saveFile=NewFile (Uploadpath, FilePath);                Item.write (SaveFile); Meg= "Success"; }Else{String FormName=Item.getfieldname (); String Formcon= Item.getstring ("Utf-8"); if(Formname.equals ("name") ) {Name=Formcon; }                    Else if(Formname.equals ("filenames") ) {filenames=Formcon; }                Else if(Formname.equals ("UpTime") ) {UpTime=Formcon; }}} Request.setattribute ("Meg", Meg); Request.setattribute ("Name", name); Request.setattribute ("Filenames", filenames); Request.setattribute ("Uptime", UpTime); Request.getrequestdispatcher ("Success.jsp"). Forward (request, response); %>

Success Page

<body>        ${requestscope.meg}        ${requestscope.name}        ${requestscope.filenames}        ${ Requestscope.uptime}  </body>

Java Upload file

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.