Javaweb file Upload and download (1)

Source: Internet
Author: User

Frequently used uploads:

Avatar upload, data sharing, etc.

Steps for uploading files

1. Specify form type for file upload form

Enctype= "Multipart/form-data"

2, form submission method must be: Post (Get method can only submit 1k size of data)

3. File field form element exists in the form

As follows:

<form action= "${pagecontext.request.contextpath/test}" method= "Post" enctype= "Multipart/form-data" >    files: <input type= "File" Name= "file1"/><br>    user name: <input type= "text" name= "username"/><br>    <input type= "Submit" value= "Submission"/>    </form>

  

First, manually implement file upload

The code is as follows

Package Com.gqx.uploadself;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream; Import Java.io.inputstreamreader;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * Manually process file uploads * @author Administrator * */public class Test extends HttpServlet {p ublic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); */* The following method is the prototype of the Request.getparameter () method that we usually use * The following method is parsed by the Request.getparameter () method *///request.getquerystring ();//Get get:username=gqxing&pwd=111// Request.getinputstream ();//Get post:inputstream/* * Now gets the file data, is a POST request, can only be used with Request.getinputstream () */// Get form (POST) data InputStream in=request.getinputstream ();//convert to character stream InputStreamReader Inreader=new InputStreamReader (in) ;//For easy reading, add a buffered stream BufferedReader (read character stream) BufferedReader Reader=new BUfferedreader (Inreader); String Str=null;while ((Str=reader.readline ())!=null) {System.out.println (str);}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}

After you start the server, submit the form and upload the file (here is a text file), you will see the output of the console of the content

If you need to get upload data, you need to parse the above results (that is, the processing of strings), each upload is such a structure, every time to parse, each upload item through the Fileitem to encapsulate the corresponding data, but so write a parser, a little trouble, At the same time is not conducive to the late maintenance of the code, others are not familiar with your code, this time you can use a component provided by Apach.

Second, the use of FileUpload components (Apach provided)

API description

-diskfileitemfactory File Upload factory class (encapsulates each request form as a single Fileitem object)

Setrepository (repository); Set the delete temp directory (when the upload file is too large, the file will be written to the temporary file, and then output from the temporary file to the specified file, and then the temporary file purged)

-servletfileupload File upload Core class, you can get all the Fileitem objects

Ismultipartcontent (Request): Determine if the file is a form type

Parserequest (Request): Get all file uploads

Setfilesizemax (Filesizemax); Set the maximum upload total file value

Setsizemax (Sizemax); Sets the maximum number of individual file uploads

Setheaderencoding ("Utf-8"); Set the encoding format of the uploaded file

-fileitem encapsulates the value of the normal form item and the value of the Upload form item

Item.getfieldname (); Get upload Form element name

Item.getstring (); Get Upload Data

Item.getstring ("Utf-8") for uploading data, processing Chinese

Item.getcontenttype (); Get upload file type "Generally used for file items"

Item.getinputstream (); Get file stream "generally used for file items"

Item.getname (); Get file name "generally used for file items"

Item.write (file); Write file "generally used for file items"

Item.delete () Delete temporary files "generally used for file entries"

Component use:

downloading components; importing jar files (Commons-fileupload-1.2.1.jar and Commons-io-1.4.jar)

The instance code is as follows

  

Package Com.gqx.uploadjar;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream; Import Java.io.inputstreamreader;import Java.io.printwriter;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.fileitemfactory;import Org.apache.commons.fileupload.fileuploadexception;import org.apache.commons.fileupload.disk.DiskFileItemFactory Import org.apache.commons.fileupload.servlet.servletfileupload;/** * File Upload component use * @author Administrator * */public Class FileUpLoad extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {request.setcharacterencoding ("Utf-8");//1, creating File Upload factory class Fileitemfactory fac=new Diskfileitemfactory ();//2. Create a file Upload Core class object Servletfileupload upload=new ServletfileuploaD (FAC);//Determine if the current form is a file upload form if (upload.ismultipartcontent (Request)) {///3), convert the request data to a collection of Fileitem objects list<fileitem> list;try {list = upload.parserequest (request);//traverse each upload entry for (Fileitem fileitem:list) {//judgment: Is it a normal form item or a File upload form if ( Fileitem.isformfield ()) {//Normal form string filename=fileitem.getfieldname ();//form element name string content=fileitem.getstring ( );//text box value System.out.println (filename+content);} else {//File upload form string filename=fileitem.getfieldname ();//form element name string Contenttype=fileitem.getcontenttype ();// File type string name=fileitem.getname ();//filename InputStream in=fileitem.getinputstream ();//File Stream System.out.println ( filename+contenttype+name+in);}}} catch (Fileuploadexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}

The results of the operation are as follows:

Case:

Implement a full file upload

1, set a single file not more than 30 trillion

2, set the total size of not more than 50 trillion

3, Upload directory: uploaded to the project resource directory under the upload directory

The code is as follows:

Package Com.gqx.uploadjar;import Java.io.bufferedreader;import Java.io.file;import java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.printwriter;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.fileitemfactory;import Org.apache.commons.fileupload.fileuploadexception;import org.apache.commons.fileupload.disk.DiskFileItemFactory Import org.apache.commons.fileupload.servlet.servletfileupload;/** * File upload complete case * @author Administrator * */public Class Fileuploadcase extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {request.setcharacterencoding ("utf-8");//1, create upload factory class Diskfileitemfactory factory =new diskfileitemfactory ();//2. Create a file upload core class Servletfileupload Upload=new servletfileupload (Factory);//[1] Set maximum file size: 30mupload.setfilesizemax (30*1024*1024);//[2] Set total file size not exceeding 50mupload.setsizemax (50*1024*1024);//Determine if File Upload form if (upload.ismultipartcontent (Request)) {///3, Convert request data to Fileitem collection try {list<fileitem> items=upload.parserequest (request);//Traverse fileitemfor (Fileitem Fileitem : items) {//Judge normal form or text form if (Fileitem.isformfield ()) {//Get element name string Fieldname=fileitem.getfieldname ();//Get value string Value=fileitem.getstring ("Utf-8"); System.out.println (fieldname+ ":" +value);} else {//File upload//Get filename string name=fileitem.getname ();//Get file directory String Basepath=getservletcontext (). Getrealpath ("/ Upload ");//Create File Object files File=new (basepath,name); fileitem.write (file); Fileitem.delete ();//delete temporary file}}} catch ( Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}

  

Javaweb file Upload and download (1)

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.