Uploading and downloading in web programs are two of the most common modules
Upload can use FileUpload's package to help complete
As: http://commons.apache.org/fileupload/.
Also fileupload relies on Commons IO, so you need to introduce the latest Commons-io package in your classpath, for: http://commons.apache.org/io/.
How is the Web application uploaded?
First, we set up a uploadfile.jsp for users to upload local information.
Where the form form enctype property needs to be set to Multipart/form-data, the method must be post, and the processing by FileUpload is submitted
<body><p align= "center" > Please select the file you want to upload </p><form id= "Form1" Name= "Form1" method= "Post" action= " FileUpload "enctype=" Multipart/form-data "><table border=" 0 "align=" center "><tr><td> Uploader: </ Td><td><input name= "name" type= "text" id= "name" size= "></TD></TR><TR><TD" > Upload file: </td><td><input name= "file" type= "file" size= "></td></tr><tr><" Td></td><td><input type= "Submit" name= "submit" value= "submit" > <inputtype= "reset" name= "reset" value= "Reset" ></td></tr></table></form></body>
The above page is referred to the Backstage fileuploadservlet processing
public class Fileuploadservlet extends HttpServlet {private static final long Serialversionuid = -7744625344830285257L;PR Ivate servletcontext sc;private String savepath;public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {this.dopost (request, response);} public void init (servletconfig config) {//an initialization parameter set in Web. XML savepath = Config.getinitparameter ("Savepath"); sc = Config.getservletcontext ();} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Set the encoded request.setcharacterencoding ("UTF-8") to the data received;D iskfileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory); try {list<fileitem> items = upload.parserequest ( Request);iterator<fileitem> ITR = Items.iterator (); while (Itr.hasnext ()) {Fileitem item = (Fileitem) itr.next (); if (Item.isformfield ()) {System.out.println ("form parameter name:" + item.getfieldname () + ", form argument value:" + Item. getString ("UTF-8"));} else {if (item.getname () = null &&!item.getname (). Equals ("")) {System.out.println ("size of the uploaded file:" + item.getsize () ); System.out.println ("Type of upload file:" + Item.getcontenttype ()),//Item.getname () returns the full path name of the uploaded file on the client System.out.println (" The name of the uploaded file: "+ item.getname ()); File Tempfile = new file (Item.getname ());//The Save path of the uploaded file = "new" (Sc.getrealpath ("/") + Savepath,tempfile.getname ()); Item.write (file); Request.setattribute ("Upload.message", "Upload file successful!") ");} else {request.setattribute ("upload.message", "no option to upload files!") ");}}}} catch (Fileuploadexception e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace (); Request.setattribute (" Upload.message "," Upload file failed! ");} Request.getrequestdispatcher ("/uploadresult.jsp"). Forward (request,response);}}
Upload will jump to uploadresult.jsp page
<body> ${requestscope[' upload.message '} <a href= "http://localhost:4848/webExercise/ uploadfile.jsp "> Uploading Files </a> </body>
It is best to attach the configuration file Web. xml
<servlet> <servlet-name>FileUploadServlet</servlet-name> <servlet-class> Com.qzp.servlet.fileuploadservlet</servlet-class> <!--Set initialization parameters-- <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </ init-param> </servlet> <servlet-mapping> <servlet-name>fileuploadservlet</ servlet-name> <url-pattern>/fileUpload</url-pattern> </servlet-mapping> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class> com.qzp.servlet.filedownloadservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/filedownservlet</ Url-pattern> </servlet-mapping>
The above is the file upload code, below we describe the file download related code
First, if the user directly to a link for download, this is feasible, but there are some unsafe factors, such as exposing the server's file storage address
Therefore, we use the following method to download the file
This is the JSP page for file download,
Why should <body> <%--be written in an out object? Because the direct write in the JSP page, will expose the server address--%> <% String filename=null; Session.setattribute ("333.txt", filename); Get the filename//Filename=getfilepath (). substring (Mb.getfilepath (). LastIndexOf ("/") +1); Out.println ("<td><a href=filedownservlet?filename=333.txt>txt file </a></td>");// Java.rar This can be changed to variable out.println ("<td><a href=filedownservlet?filename=a.txt> plain file </a></td > "); Out.println ("<td><a href=filedownservlet?filename=area.xml>xml config file </a></td>"); Out.println ("</tr>"); } %> </body>
The servlet code that handles this page is as follows
public class Filedownloadservlet extends HttpServlet {private static final String Content_Type = "text/html; Charset=utf-8 "; Initialize Global Variables public void init () throws Servletexception {}//process the HTTP Get request PU Blic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {Response.setcontenttype (Content_Type); Get the name of the downloaded file//string filename=request.getparameter ("filename"); Solve the problem of Chinese garbled string Filename=new string (request.getparameter ("filename"). GetBytes ("Iso-8859-1"), "Utf-8"); Create the File Object file File=new file ("This.getservletcontext (). Getrealpath ("/") +" uploads/"+filename); Set the encoding method of the response Response.setcontenttype ("Application/x-msdownload"); Specify the size of the file to download response.setcontentlength ((int) file.length ()); Set additional filename//Response.setheader ("Content-disposition", "attachment;filename=" +filename); Fix Chinese garbled response.setheader ("Content-disposition", "Attachment;filename=" +new String (filename.getbytes ("Utf-8 ")," iso-8859-1 "); read out file to I/O stream fileinputstream fis=new fileinputstream (file); Bufferedinputstream buff=new bufferedinputstream (FIS); byte [] b=new byte[1024];//is equivalent to our cache long k=0;//This value is used to calculate how many bytes are currently actually downloaded//from the response object to get the output stream, ready to download Outputstrea M Myout=response.getoutputstream (); Start loop Download while (K<file.length ()) {int j=buff.read (b,0,1024); K+=j; Writes the data in B to the client's memory Myout.write (B,0,J); }//will write data to the client's memory, flush to disk myout.flush (); }//process the HTTP Post request public void DoPost (HttpServletRequest request, httpservletresponse response) throw S servletexception, IOException {doget (request, response); }//clean up resources public void Destroy () {}}
Last posted on the upload and download page
To upload files:
Download the file:
A detailed description of the upload and download functions in the Web program