FileUpload Series: (3) file upload and download examples

Source: Internet
Author: User


The example consists of 1 servlets and 3 JSPs.


1, Fileservlet

package com.rk.web.servlet;import java.io.file;import java.io.fileinputstream;import  java.io.ioexception;import java.io.inputstream;import java.io.outputstream;import  Java.net.urlencoder;import java.util.hashmap;import java.util.list;import java.util.map;import  java.util.UUID;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.disk.DiskFileItemFactory;import  org.apache.commons.fileupload.servlet.servletfileupload;/** *  processing file upload and download  * */public  Class fileservlet extends httpservlet {public void doget (HttpServletRequest  request, httpservletresponse response) Throws servletexception, ioexception {//  gets the request parameter:  distinguishes between different operation types String method = request.getparameter (" Method ");if  (" Upload ". Equals (method))  {//  upload upload (request,response);} else if  ("Downlist". Equals (method))  {//  Enter 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, ioexception {try {// 1.   Create factory Object Fileitemfactory factory = new diskfileitemfactory ();// 2.  File Upload core tool class Servletfileupload upload = new servletfileupload (Factory);//  Set 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");//  to Chinese file encoding processing//  judgment if  (Request )) &NBSP;{//&NBsp;3.  converts the request data to the list collection list<fileitem> list = upload.parserequest (request);//  traversal for   (Fileitem item : list) {//  judgment: Plain Text data if  (Item.isformfield ()) {//  get name string  name = item.getfieldname ();//  Gets the value string value = item.getstring (); System.out.println (value);}  //  file Form Item else {/********  file upload  ***********/// a.  get file name String name  = item.getname ();// ----deal with the name of the upload filename----// a1.  first to get a unique tag string id =  Uuid.randomuuid (). toString ();// a2.  stitching file name name = id +  "#"  + name;//  b.  Get upload directory String basepath = getservletcontext (). Getrealpath ("/upload");// c.   Create a File object to upload File file = new file (basepath,name);// d.  upload item.write (file); Item.delete ();  //  Delete the temporary file generated when the component runs}}}} catch  (exception e)  { E.printstacktrace ();}} /** * 2.  into the download list  */private void downlist (httpservletrequest request,  Httpservletresponse response) throws servletexception, ioexception {//  Realization idea: Get the file name of all files in upload directory first, then save; jump to down.jsp list//1.  Initialize map collection map< file name with unique tag,  short file name >  ; Map<string,string> filenames = new hashmap<string,string> ();//2.  get the upload directory, And all of its files under the file name String bathpath = getservletcontext (). Getrealpath ("/upload");//  directory file  File = new file (Bathpath);//  directory, all Filenames string list[] = file.list ();//  Traverse, Package 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);//  Package 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 the file name that the user downloaded ( Append data after URL address, get) string filename = request.getparameter ("FileName"); filename = new  string (Filename.getbytes ("iso8859-1"), "UTF-8");//  get the Upload directory path First string basepath =  Getservletcontext (). Getrealpath ("/upload");//  get a file stream inputstream in = new  FileInputStream (New file (basepath,filename));//  If the file name is Chinese, URL encoding is required filename =  Urlencoder.encode (filename,  "UTF-8");//  set the download response header Response.setheader ("Content-disposition",  " Attachment;filename= " + filename);//  get 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);}}



2, index.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >



<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >



4, downlist.jsp

<%@ page language= "java"  import= "java.util.*"  pageencoding= "UTF-8"%><% @taglib  uri= "Http://java.sun.com/jsp/jstl/core"  prefix= "C"  %><! doctype html public  "-//w3c//dtd html 4.01 transitional//en" >









FileUpload Series: (3) file upload and download examples

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.