Requirements:
Provide file upload, upload size is required
There is a page showing the uploaded list
You can download the file in the upload list.
The first is the JSP page, one is the main page, whether, there are two choices--upload and download a list
The code is as follows: (index.jsp)
<body> <a href= "${pagecontext.request.contextpath}/demo/upload.jsp" > File upload </a> <a href= "${pagecontext.request.contextpath}/fileservlet?method=downlist" > File download </a> </body>
And then the File upload page.
<%@ 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" >
followed by the servlet processing of the file (on the server side I created a folder (upload) to hold the upload file)
Package Com.gqx.demoservlet;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException;import Java.io.inputstream;import Java.io.outputstream;import Java.io.printwriter;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.fileuploadexception;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;public class Fileservlet extends HttpServlet {public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Get request parameters, Distinguish what method string Method=request.getparameter ("method") is, if ("Upload". Equals (method)) {//upload try {upload (request,response );} catch (ExceptiOn e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if ("Downlist". Equals (method)) {//download downlist (request,response);} if ("Down". Equals (method)) {try {down (request,response)} catch (Exception e) {//TODO auto-generated catch blocke.prints Tacktrace ();}}} private void Upload (HttpServletRequest request, httpservletresponse response) throws Exception {//TODO auto-generated Me Thod STUB//1, creating factory class objects Diskfileitemfactory factory=new diskfileitemfactory ();//2, creating a file Core Download class Servletfileupload upload= New Servletfileupload (factory);//Set the file size limit parameter Upload.setfilesizemax (10*1024*1024); Set the maximum upload capacity of a single file Upload.setsizemax (50*1024*1024);//Set the maximum upload capacity of the total file upload.setheaderencoding ("Utf-8");//encode Chinese files// Determine if the form is committed if (upload.ismultipartcontent (Request)) {//3), convert the request data to the list collection list<fileitem> list= Upload.parserequest (request);//Traverse for (Fileitem fileitem:list) {//To determine if normal text data if (Fileitem.isformfield ()) {// Plain Text data string name=fileitem.getfieldname (); String value=fileitem.getstring (); System.out.println (name+ ":" +value);} else {//File upload//Get file name string Name=fileitem.getname ();/*** handle upload file Rename problem **///a, first get unique tag string id=uuid.randomuuid (). ToString ();//Generate a unique set of string//b, stitching file name name=id+ "#" +name;//get the File upload directory string Basepath=getservletcontext (). Getrealpath ("/ Upload ");//create File Upload object files file =new file (basepath,name);//Start uploading fileitem.write (file);//delete temporary files generated when component is running Fileitem.delete ();}}} Response.sendredirect (Request.getservletcontext (). Getcontextpath () + "/demo/index.jsp");} private void Downlist (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {/ /TODO auto-generated Method stub/** realize the idea: the spot area upload directory under the file name of all files, in the save, jump to Down.jsp list show *///1. Initializes the map collection map< contains a unique tag file name, short filename >; Map<string,string> filemap=new hashmap<string, string> ();//2. Get the file name of the upload directory and all of its files String basepath= Getservletcontext (). Getrealpath ("/upload");//directory file File=new file (basepath);//directory all filenames under string list[]=file.list (); /Traverse if (list!=null && list.length > 0) {//Resolve server under File name for (int i=0;i<list.length;i++) {//Full name string filename=list[i];//short name string shortname=filename.substring (Filename.indexof ("#") +1);//Package Filemap.put (FileName, shortname);}} 3. Save to request Domain Filenamessrequest.setattribute ("fileNames", Filemap); Request.getrequestdispatcher ("/demo/ Downlist.jsp "). Forward (request, response);} /** * Processing File Download * @param request * @param response */private void down (httpservletrequest request, HttpServletResponse Respon SE) throws Exception {//TODO auto-generated method stub//Get the file name downloaded by the user (appended, get request after URL) String filename= Request.getparameter ("FileName"); Filename=new string (Filename.getbytes ("iso-8859-1"), "Utf-8");//Get 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 in Chinese, URL encoding filename =urlencoder.encode (filename, "UTF-8");//Set the downloaded response header Response.setheader (" Content-disposition "," attachment;filename= "+ fileName);//Get response byte stream OutputStream Out=response.getoutputstream ( ); byte[] bytes=new byte[1024];int len=-1;while (len=in.read(bytes))! =-1) {out.write (Bytes,0,len);} Out.close (); In.close ();} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}} With it, you can get a list of files and download pages
<%@ 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" >Effect
Upload the list with the downloaded file
File Upload and download case