Javaweb File upload Download function Example Analysis _java

Source: Internet
Author: User

In the Web application system development, the file uploads and the downloading function is the very commonly used function, today says the Javaweb file uploads and the downloading function realization.

1. Upload a simple example

Jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <!
DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" >
 
 

Servlet

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {try
 
 {//1. Get parser factory Diskfileitemfactory factory = new Diskfileitemfactory ();
 
 2. Get parser Servletfileupload upload = new Servletfileupload (factory);
 3. To determine the type of upload form if (!upload.ismultipartcontent (Request)) {//Upload form for ordinary form, then in accordance with the traditional way to get the data can return; ///For upload form, then call parser to parse upload data list<fileitem> List = upload.parserequest (request); Fileitem//Traversal list to be used to encapsulate the first upload entry data Fileitem object for (Fileitem item:list) {if (Item.isformfield ()) {//Get the generic entry Str ing name = Item.getfieldname ();
 Gets the name of the entry String value = Item.getstring ();
 SYSTEM.OUT.PRINTLN (name + "=" + value); }else{//Get uploaded input String filename = item.getname ()//Get upload filename C:\Documents and settings\thinkpad\ desktop \1.txt filename = fil
 Ename.substring (Filename.lastindexof ("\") +1); InputStream in = Item.getinputstream ();
 Get uploaded data int len = 0;
 
 BYTE buffer[]= new byte[1024]; The directory used to save uploaded files should prohibit direct access to the String Savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");
 
 System.out.println (Savepath); FileOutputStream out = new FileOutputStream (Savepath + "/" + filename);
 Writes a file to the upload directory while ((Len=in.read (buffer) >0) {out.write (buffer, 0, Len);
 } in.close ();
 Out.close ();
 Request.setattribute ("message", "upload success");
 }}catch (Exception e) {request.setattribute ("message", "Upload failed");
 E.printstacktrace ();

 }

 
 }

2. After the modified upload function:

Precautions:

1, upload the file name of Chinese garbled and uploaded data in Chinese garbled
Upload.setheaderencoding ("UTF-8"); Solve the file name of the upload of Chinese garbled
form for file upload, set request encoding is invalid, can only be converted manually
1.1 Value = new String (value.getbytes ("iso8859-1"), "UTF-8");
1.2 String value = item.getstring ("UTF-8");

2. To ensure server security, upload files should be placed in the outside can not directly access the directory

3, in order to prevent the occurrence of file coverage, to upload files to produce a unique file name

4. To prevent the occurrence of too many files under a directory, use the hash algorithm to break up the storage

5. To limit the maximum size of uploaded files, you can do this by: Servletfileupload.setfilesizemax (1024) and by capturing:
fileuploadbase.filesizelimitexceededexception exception to give user friendly hints

6. To ensure that temporary files are deleted, be sure to call the Item.delete method after you have finished processing the uploaded file

7. To limit upload file type: When the upload file name, determine whether the suffix name is legal

8. Monitor File Upload progress:

 Servletfileupload upload = new Servletfileupload (factory);
 Upload.setprogresslistener (New Progresslistener () {public
 void update (Long pbytesread, long pcontentlength, int ARG2) {
  System.out.println ("File size is: + Pcontentlength +", currently processed: "+ pbytesread);
 }}"
 ;
 

9. Transfer entries on dynamically added files on a Web page

 function Addinput () {
  var div = document.getElementById ("file");
  
  var input = document.createelement ("input");
  input.type= "File";
  Input.name= "filename";
  
  var del = document.createelement ("input");
  Del.type= "button";
  del.value= "Delete";
  Del.onclick = function d () {
  this.parentNode.parentNode.removeChild (this.parentnode);
  }
  
  
  var innerdiv = document.createelement ("div");
  
  
  Innerdiv.appendchild (input);
  Innerdiv.appendchild (del);
  
  Div.appendchild (Innerdiv);
  }

Upload jsp:

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

Upload servlet

public class UploadServlet1 extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Res Ponse) throws Servletexception, IOException {//request.getparameter ("username");//**** error Request.setcharacterencodi Ng ("UTF-8");
 
 form for file upload, set request encoding invalid//Get upload File save directory String Savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");
 try{Diskfileitemfactory factory = new Diskfileitemfactory ();
 
 Factory.setrepository (New File (This.getservletcontext (). Getrealpath ("/web-inf/temp"));
 Servletfileupload upload = new Servletfileupload (factory); /*upload.setprogresslistener (New Progresslistener () {public void update (long pbytesread, long pcontentlength, int arg2)
 {System.out.println ("File size is: + Pcontentlength +", currently processed: "+ pbytesread); }); */upload.setheaderencoding ("UTF-8");
 Solve the upload file name of Chinese garbled if (!upload.ismultipartcontent (Request)) {//In accordance with the traditional way to get data return;
 }/*upload.setfilesizemax (1024); Upload.setsizemax (1024*10); * * List<fileitem> list = upload.parserequest (request);
  for (Fileitem item:list) {if (Item.isformfield ()) {//fileitem, the data String name = Item.getfieldname () of the normal entry is encapsulated.
  String value = item.getstring ("UTF-8");
  Value = new String (value.getbytes ("iso8859-1"), "UTF-8");
 SYSTEM.OUT.PRINTLN (name + "=" + value); }else{//fileitem encapsulates the upload file String filename = item.getname ();//The files submitted by different browsers are not the same c:\a\b\1.txt 1.txt System.out.println
  (filename);
  if (Filename==null | | Filename.trim (). Equals ("")) {continue;
  
  filename = filename.substring (filename.lastindexof ("\") +1);
  InputStream in = Item.getinputstream (); String savefilename = makefilename (filename); Get file saved name String Realsavepath = Makepath (Savefilename, Savepath);
  Get the file save directory FileOutputStream out = new FileOutputStream (Realsavepath + "\" + savefilename);
  byte buffer[] = new byte[1024];
  int len = 0;
  while (len=in.read (buffer) >0) {out.write (buffer, 0, Len);
  } in.close ();
  Out.close (); Item.deletE ();
 Delete temporary file}}catch (Fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace (); Request.setattribute ("message", "File exceeds maximum value!!!
 ");
 Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
 Return
 catch (Exception e) {e.printstacktrace ();
 } public string Makefilename (string filename) {//2.jpg return Uuid.randomuuid (). toString () + "_" + filename;
 public string Makepath (string filename,string savepath) {int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf; 0--15 int dir2 = (hashcode&0xf0) >>4; 0-15 String dir = savepath + "\" + Dir1 + "\" + Dir2;
 Upload\2\3 upload\3\5 file = new file (dir);
 if (!file.exists ()) {file.mkdirs ();
 } return dir;

 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 Doget (request, response);

 }

}

3. Download function

List all download files for Web site public
class Listfileservlet extends HttpServlet {public

 void doget (HttpServletRequest request, HttpServletResponse response)
 throws Servletexception, IOException {
 
 String filepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");
 Map map = new HashMap ();
 ListFile (New File (filepath), map);
 
 Request.setattribute ("map", map);
 Request.getrequestdispatcher ("/listfile.jsp"). Forward (request, response);
 
 public void ListFile (file File,map Map) {

 if (!file.isfile ()) {
 File files[] = File.listfiles ();
 for (File f:files) {
 listfile (f,map);
 }
 } else{
 String realname = File.getname (). substring (File.getname (). IndexOf ("_") +1);//9349249849-88343-8344_ _ every _ Da avi
 Map.put (File.getname (), realname);
 }
 
 

 public void DoPost (HttpServletRequest request, httpservletresponse response)
 throws Servletexception, IOException {

 doget (request, response);
 }

}

JSP display

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%
@taglib prefix= "C" uri= "http://" Java.sun.com/jsp/jstl/core "%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
 
 

Download processing servlet

public class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse re Sponse) throws Servletexception, IOException {String filename = request.getparameter ("filename");//23239283-92489
 -Avatar. avi filename = new String (filename.getbytes ("iso8859-1"), "UTF-8");
 
 String path = Makepath (Filename,this.getservletcontext (). Getrealpath ("/web-inf/upload"));
 File File = new file (path + "\" + filename); if (!file.exists ()) {Request.setattribute ("message"), the resource you are downloading has been deleted!!
 ");
 Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
 Return
 String realname = filename.substring (Filename.indexof ("_") +1);
 
 Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (realname, "UTF-8"));
 FileInputStream in = new FileInputStream (path + "\" + filename);
 OutputStream out = Response.getoutputstream ();
 byte buffer[] = new byte[1024];
 int len = 0; while ((Len=in.read (buffer)) >0) {Out.write (bUffer, 0, Len);
 } in.close ();
 Out.close ();
 public string Makepath (string filename,string savepath) {int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf; 0--15 int dir2 = (hashcode&0xf0) >>4; 0-15 String dir = savepath + "\" + Dir1 + "\" + Dir2;
 Upload\2\3 upload\3\5 file = new file (dir);
 if (!file.exists ()) {file.mkdirs ();
 } return dir;

 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
 Doget (request, response);
 }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.