Java File upload download function implementation Code _java

Source: Internet
Author: User
Tags file upload uuid

This example for you to share the file upload download Java implementation code for your reference, the specific contents are as follows

Front desk:

1. Submission Method:Post
2. The form has the file to upload the form item: <input type= "file"/>
3. Specify the form type:
Default type: enctype= "application/x-www-form-urlencoded"
File Upload type: multipart/form-data

FileUpload

File upload function is more commonly used in the development, Apache also provides file upload components!
FileUpload components:
1. Download source
2. Introduction of JAR file in project
Commons-fileupload-1.2.1.jar "File Upload component Core jar package"
Commons-io-1.4.jar "encapsulates the relevant tool classes for file processing"

Use:

public class Uploadservlet extends HttpServlet {//upload directory, save uploaded resources public void doget (HttpServletRequest request, HTT
   Pservletresponse response) throws Servletexception, IOException {/********* file Upload component: Processing file upload ************/try { 1.
   File Upload Factory Fileitemfactory factory = new Diskfileitemfactory (); 2.

   Create File upload core tool class Servletfileupload upload = new Servletfileupload (factory);
   First, set the maximum size allowed for a single file: 30M Upload.setfilesizemax (30*1024*1024);
   Second, set the File upload form to allow the total size: 80M Upload.setsizemax (80*1024*1024);
   Third, set the upload form file name code//equivalent: Request.setcharacterencoding ("UTF-8");


   Upload.setheaderencoding ("UTF-8"); 3. Determine if the current form is a file upload form if (upload.ismultipartcontent) {//4. Convert the request data to a Fileitem object, and then use a collection package list<fileitem& Gt
    List = Upload.parserequest (request); Traversal: Get each uploaded data for (Fileitem item:list) {//Judge: Normal text data if (Item.isformfield ()) {//Normal text data Str ing fieldName = item.getfieldname (); Form element name String COntent = Item.getstring (); The form element name, corresponding data//item.getstring ("UTF-8");
     Specifies the encoding System.out.println (FieldName + "" + content); //Upload file (file stream)----> upload to upload directory else {//plain text data String fieldName = Item.getfieldname ();//table cell   element name String name = Item.getname ();  FileName String content = item.getstring (); The form element name, the corresponding data String type = Item.getcontenttype (); File type InputStream in = Item.getinputstream ();
       Upload file Stream * * Four, file name duplicate * for different user readme.txt files, do not want to overwrite!
       * Background processing: To add a unique tag to the user!
      *//A. Randomly generate a unique tag String id = uuid.randomuuid (). toString ();

      B. stitching name with filename = id + "#" + name;
      Get upload Base path String path = Getservletcontext (). Getrealpath ("/upload");

      Creates the target file, filename = new file (path,name);
      Tool class, File upload item.write (files); Item.delete ();
     Delete system-generated temporary files System.out.println (); }} else {System.out.println ("current tableSingle not file upload form, processing failed!
   ");
  } catch (Exception e) {e.printstacktrace (); 
  }//manual implementation process private void upload (HttpServletRequest request) throws IOException, Unsupportedencodingexception { /* Request.getparameter (""); Get/post request.getquerystring (); Gets the data submitted by get Request.getinputstream (); Get post submitted data * */*********** manually get file Upload form data ************///1.
  Gets the form data stream InputStream in = Request.getinputstream (); 2.
  Convert stream InputStreamReader instream = new InputStreamReader (in, "UTF-8"); 3.
  Buffered stream BufferedReader reader = new BufferedReader (instream);
  Output data String str = NULL;
  while (str = Reader.readline ())!= null) {System.out.println (str);
  }//Close Reader.close ();
  Instream.close ();
 In.close (); 
  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 This.doget (request, response);
 }

}

Case:

index.jsp

<body> 
  <a href= "${pagecontext.request.contextpath}/upload.jsp" > File upload </a>
  <a href= "${ PageContext.request.contextPath}/fileservlet?method=downlist "> File download </a> 

</body>

upload.jsp

<body> 
  <form name= "frm_test" action= "${pagecontext.request.contextpath}/fileservlet?method=upload" Method= "POST" enctype= "Multipart/form-data" >
   <%--<input type= "hidden" name= "method" value= "Upload" >--%>

   user name: <input type= "text" name= "UserName" > <br/>
  File: <input type= "file" Name= "File_ IMG "> <br/>

  <input type=" Submit "value=" submitted ">
  </form>
 </body>

Fileservlet.java

/** * Process file upload and download * @author Jie.yuan */public class Fileservlet extends HttpServlet {public void doget (Httpservle  Trequest requests, httpservletresponse response) throws Servletexception, IOException {//Get request parameters: differentiate between different operation types String
  method = Request.getparameter ("method");
  if ("Upload". Equals (method)) {//upload upload (request,response);
  else if ("Downlist". Equals (method)) {//Enter the download list downlist (request,response);
  else if (' Down '. Equals (method)) {//Download down (request,response); }/** * 1. Upload/private void upload (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcepti
   On {try {//1. Create Factory object Fileitemfactory factory = new Diskfileitemfactory (); 2.
   File Upload core tool class Servletfileupload upload = new Servletfileupload (factory); Set the size limit parameter Upload.setfilesizemax (10*1024*1024);  Single File size limit Upload.setsizemax (50*1024*1024);  Total file size limit upload.setheaderencoding ("UTF-8");
Code processing for Chinese files
   Judge if (upload.ismultipartcontent) {//3. Convert request data to list collection List<fileitem> list = Upload.par
    Serequest (Request); Traversal for (Fileitem item:list) {//judgment: Normal text data if (Item.isformfield ()) {//get name String name = it
      Em.getfieldname ();
      Gets the value String value = item.getstring ();
     System.out.println (value);
      }//File table single else {/******** file upload ***********///A. Get file name String name = Item.getname (); ----process----//A1 The name of the upload filename.
      First get a unique tag String id = uuid.randomuuid (). toString (); A2.      

      Stitching filename name = id + "#" + name;
      B. Get upload directory String basepath = Getservletcontext (). Getrealpath ("/upload");
      C. Create the file object to upload files = new filename (basepath,name);
      D. Upload item.write (file); Item.delete ();
  Deletes temporary files generated by the component Runtime}} and catch (Exception e) {e.printstacktrace (); }/** * 2. Go to download list * * private void DowNlist (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Realization idea: Get Uplo first The file name of all files in the ad directory, then save; jump to down.jsp list to show//1.
  Initializes the map collection map< contains a unique tag file name, short file name >;

  map<string,string> fileNames = new hashmap<string,string> (); 2.
  Gets the filename String bathpath = Getservletcontext (). Getrealpath ("/upload") of the uploaded directory and all the files under it.
  Directory File File = new file (Bathpath);
  directory, all filename String list[] = File.list (); Traversal, encapsulating if (list!= null && list.length > 0) {for (int i=0; i<list.length; i++) {//Full name String
    FileName = List[i];
    Short name String shortname = filename.substring (Filename.lastindexof ("#") +1);
   Encapsulation Filenames.put (FileName, shortname); }//3.
  Save to request Domain Request.setattribute ("fileNames", fileNames); 4.

 Forwarding Request.getrequestdispatcher ("/downlist.jsp"). Forward (request, response); }/** * 3. Processing download/private void Down (HttpServletRequest request, HttpServletResponse ResponSE) throws Servletexception, IOException {//Get user-downloaded file name (append data after URL address) String fileName = Request.getparameter ("fi
  Lename ");

  FileName = new String (filename.getbytes ("iso8859-1"), "UTF-8");
  First get the upload directory path String basepath = Getservletcontext (). Getrealpath ("/upload");

  Gets a file stream inputstream in = new FileInputStream (new file (Basepath,filename));
  If the filename is Chinese, url encoding filename = urlencoder.encode (filename, "UTF-8") is required;

  Set Download response header Response.setheader ("Content-disposition", "attachment;filename=" + fileName);
  Gets the response byte stream outputstream out = Response.getoutputstream ();
  Byte[] B = new byte[1024];
  int len =-1;
  while (len = In.read (b))!=-1) {out.write (b, 0, Len);
  }//Close Out.close ();


 In.close (); 
  public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 This.doget (request, response);
 }

}

The above is the entire content of this article, I hope to help you learn.

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.