Javaweb file upload and download function analysis _java

Source: Internet
Author: User
Tags file copy int size readline temporary file storage first row

Uploading and downloading files in the development process is very common. Here's a quick summary:

1. File upload must meet the conditions:
A, the method of the page form must be post because the data for the get transfer is too small
b, the enctype of the page form must be multipart/form-data type
C, the form to provide the upload input fields
Code details: Client form: <form enctype= "Multipart/form-data"/>
(without this attribute, the file path read by the server will vary depending on the browser)
Service-side ServletInputStream Is=request.getinputstream (); Get the request body content in flow, further parsing.

2. Upload the details of the file:
(1) Why the form type is set: Multipart/form-data. is not a Key=value value to set this form to pass. The byte code is passed.
The corresponding relationship between the form and the request:

As you can see, after setting the form type: Multipart/form-data, initialize the file of your choice in the HTTP request body to binary, as in the case of a string of random strings below the cookie in the image above.
Note, however, that there are two special characters in the file bytecode (that is, a string of random strings) in the identity file, that is, the first row of content file headers and one line of blank lines. The third line after that is the binary file content.
So when the server accepts the file uploaded by the client, the first three lines are removed when the file binary in the HTTP request parameter is obtained.

3. Manually parse the upload of TXT file:

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
 /** * If the type of a form is post and enctype is multipart/form-date * All data is passed to the server in binary form.
 * So Req.getparameter ("xxx") is always null.  * Only through Req.getinputstream () to obtain data, get the body of the data * * @author WANGXI * */public class Upservlet extends HttpServlet {public void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {req.setcharacte
  Rencoding ("UTF-8");
  String txt = req.getparameter ("txt");//Returns a null SYSTEM.ERR.PRINTLN ("TXT is:" +txt);
  System.err.println ("=========================================");
InputStream in = Req.getinputstream ();
Byte[] b= new byte[1024];
int len = 0; while ((Len=in.read (b))!=-1) {//String s = new String (B,0,len);
System.err.print (s);
  } bufferedreader br = new BufferedReader (new InputStreamReader (in)); String firstline = Br.readline (),//Read the first row, and the first row is a separator symbol, that is, a random string, string fileName = Br.readline (), or the second line of file information, from which the filename filename is intercepted = Filename.substring (Filename.lastindexof ("\") +1);//xxxx.txt "fileName = filename.substring (0,filename.length ()-1

  );
  Br.readline ();
  Br.readline ();
  String data = null;
  Gets the current project's run path String ProjectPath = Getservletcontext (). Getrealpath ("/up");
  PrintWriter out = new PrintWriter (projectpath+ "/" +filename);
   while ((Data=br.readline ())!=null) {if (Data.equals (firstline+ "--")) {break;
  } out.println (data);
 } out.close ();

 }
}

4. Use apache-fileupload processing file upload:
framework: Refers to a code encapsulation of the business that is frequently handled by the user. Make it easy for users to invoke.
Current file Upload (frame) component:
Apache--fileupload-
orialiy–cos–2008 ()-
jsp-smart-upload–200m.
Uploading Files with FileUpload:

Need to import a third party package:

apache-fileupload.jar– File Upload core package.
apache-commons-io.jar– This package is a fileupload-dependent package. It is also a toolkit.

Core classes:

diskfileitemfactory– Set disk space to save temporary files. Just a class.
Servletfileupload-File Upload Core class, this class receives request, and resolves Reqeust.
Servletfileupload.parserequest (requdest)-list<fileitem>
Note: A fileitem is the beginning of an identity:---------243243242342 to------------------245243523452-is a fileitem

First step: Import the package:

Step Two: write a servlet to complete the Dopost method

/** * Diskfileitemfactory Constructs two parameters * First parameter: sizethreadhold-set cache (memory) Save how many bytes of data, the default is 10K * If a file is not greater than 10K, the direct use of memory directly to save files on it.
 * If a file is larger than 10K, you need to save the file to the Temp directory first. * The second parameter File refers to the temporary directory location * */public class Up2servlet extends HttpServlet {public void DoPost (HttpServletRequest req, Htt
  Pservletresponse resp) throws Servletexception, IOException {req.setcharacterencoding ("UTf-8");
  Gets the path to the project String path = Getservletcontext (). Getrealpath ("/up"); The first step is to declare the Diskfileitemfactory factory class, which is used to set up a temporary directory on the disk that refers to diskfileitemfactory disk = new Diskfileitemfactory (1024*10,new File (
  "/home/wang/"));
  Step two: Declare Servletfileupoload, receive the above temporary directory servletfileupload up = new Servletfileupload (disk);
   Step three: Parse request try {list<fileitem> List = up.parserequest (req);
   If you fileitem file = List.get (0) on a document;
   Gets the filename, with the path String fileName = File.getname ();
   FileName = filename.substring (Filename.lastindexof ("\") +1);
   Gets the type of the file String FileType = File.getcontenttype (); Gets the byte code for the file InpuTstream in = File.getinputstream ();
   Declares output byte stream outputstream out = new FileOutputStream (path+ "/" +filename);
   File copy byte[] b = new byte[1024];
   int len = 0;
   while ((Len=in.read (b))!=-1) {out.write (B,0,len);

   } out.close ();

   Long size = File.getinputstream (). available ();
   Delete the uploaded temporary file file.delete ();
   Display Data Resp.setcontenttype ("Text/html;charset=utf-8");
   PrintWriter op = resp.getwriter ();
   Op.print ("File Upload success <br/> filename:" +filename);
   Op.print ("<br/> file type:" +filetype);



  Op.print ("<br/> File size (bytes)" +size);
  catch (Exception e) {e.printstacktrace ();

 }

 }

}

5. Use the framework to upload multiple files:

The first step: Modify the page's form for multiple input type= "file"

<form action= "<c:url value= '/up3servlet '/>" method= "post" enctype= "Multipart/form-data" >
  File1: <input type= "file" name= "TXT" ><br/>
  file2:<input type= "file" name= "TXT" ><br/>
  < Input type= "Submit"/>
 </form>

Step Two: traverse list

public class Up3servlet extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse respons
  E) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8");
  String path = Getservletcontext (). Getrealpath ("/up");
  Statement disk Diskfileitemfactory disk = new Diskfileitemfactory ();
  Disk.setsizethreshold (1024*1024);
  Disk.setrepository (New File ("d:/a"));
  Declares the servlet servletfileupload of parsing requst up = new Servletfileupload (disk);
   try{//Parse requst list<fileitem> List = up.parserequest (request); Declares the data of a list<map> package uploaded file list<map<string,string>> ups = new Arraylist<map<string,string
   >> ();
    for (Fileitem file:list) {map<string,string> mm = new hashmap<string, string> ();
    Get filename String filename = file.getname ();
    FileName = filename.substring (Filename.lastindexof ("\") +1);
    String FileType = File.getcontenttype ();
    InputStream in = File.getinputstream (); INT size = in.available ();
    Use tool class Fileutils.copyinputstreamtofile (In,new File (path+ "/" +filename));
    Mm.put ("filename", filename);
    Mm.put ("FileType", FileType);

    Mm.put ("Size", "" "+size);
    Ups.add (mm);
   File.delete ();
   } request.setattribute ("Ups", UPS);

  Forwarding Request.getrequestdispatcher ("/jsps/show.jsp"). Forward (request, response);
  }catch (Exception e) {e.printstacktrace ();

 }
 }
}

As above is the common practice of uploading files. Now we are looking at other FileUpload APIs.

Determines whether a fileitem is a file (Type=file) object or a text (Type=text|checkbox|radio) object:
Boolean Isformfield () if it is text|checkbox|radio|select this value is true.

6. Processing of pictures with descriptive information

public class Updescservlet extends HttpServlet {public void DoPost (HttpServletRequest request, HttpServletResponse resp Onse) throws Servletexception, IOException {request.setcharacterencoding ("UTF-8");//Can get Chinese filename String path = Getse
  Rvletcontext (). Getrealpath ("/up");
  Diskfileitemfactory disk = new Diskfileitemfactory ();
  Disk.setrepository (New File ("d:/a"));
   try{servletfileupload up = new Servletfileupload (disk);
   list<fileitem> list = up.parserequest (request); for (Fileitem file:list) {//First step: Determine if it is a normal table single if (File.isformfield ()) {String fileName = File.getfieldname ();//&L T;input type= "text" name= "desc" >=desc String value = file.getstring ("UTF-8");/By default read data in ISO mode SYSTEM.ERR.PRINTL
    N (filename+ "=" +value);
     }else{//description is a file String FileName = File.getname ();
     FileName = filename.substring (Filename.lastindexof ("\") +1);
     File.write (New File (path+ "/" +filename));
     SYSTEM.ERR.PRINTLN ("filename is:" +filename); System. err.println ("File size is:" +file.getsize ());
    File.delete ();
  }}catch (Exception e) {e.printstacktrace ();

 }
 }

}

7. File Upload Performance improvement
when parsing request gets a collection of Fileitem, use:

Fileitemiterator it= Up.getitemiterator (Request);

than using

list<fileitem> list = up.parserequest (request);

Performance is much better.
Sample code:

public class Fastservlet extends HttpServlet {public


 void DoPost (HttpServletRequest request, HttpServletResponse Response)
   throws Servletexception, IOException {
  request.setcharacterencoding ("UTF-8");
  String path = Getservletcontext (). Getrealpath ("/up");
  Diskfileitemfactory disk = 
    new Diskfileitemfactory ();
  Disk.setrepository (New File ("d:/a"));
  try{
   servletfileupload up = new Servletfileupload (disk);
   The following is the iterator pattern
   fileitemiterator it= up.getitemiterator (request);
   while (It.hasnext ()) {
    Fileitemstream item = It.next ();
    String fileName = Item.getname ();
    Filename=filename.substring (Filename.lastindexof ("\") +1);
    InputStream in = Item.openstream ();
    Fileutils.copyinputstreamtofile (in,new File (path+ "/" +filename));
   }
  catch (Exception e) {
   e.printstacktrace ();}}}



8. Download the file
can be either get or post.

public void DoPost (HttpServletRequest req, HttpServletResponse resp)
   throws Servletexception, IOException {
  Req.setcharacterencoding ("UTF-8");
  String name = Req.getparameter ("name");
  First step: Set the type of response
  resp.setcontenttype ("Application/force-download");
  Second Read file
  String path = Getservletcontext (). Getrealpath ("/up/" +name);
  InputStream in = new FileInputStream (path);
  Sets the response header
  //URL encoding name
  = Urlencoder.encode (name, "UTF-8") for the filename;
  Resp.setheader ("Content-disposition", "attachment;filename=" +name);
  Resp.setcontentlength (In.available ());

  Step three: Start file copy
  outputstream out = Resp.getoutputstream ();
  Byte[] B = new byte[1024];
  int len = 0;
  while ((Len=in.read (b))!=-1) {
   out.write (B,0,len);
  }
  Out.close ();
  In.close ();
 }

When using the Java EE Popular frame

It is simpler to use the inner package of the framework to complete the upload download:

Struts2 finished uploading.

When you use STRUTS2 for development, the imported jar package is not hard to find Commons-fileupload-1.3.1.jar packages. Through the above study we can already use it to upload the file to download. However, the STRUTS2 is further encapsulated.

View

<form action= "Fileupload.action" method= "post" enctype= "Multipart/form-data" >
  Username: <input Type= "text" name= "username" ><br>
  file: <input type= "file" name= "file" ><br>

  <input Type= "Submit" value= "Submit" >
 </form>  

Controller

public class Fileuploadaction extends Actionsupport {private String username;

 Note that file does not refer to the file itself uploaded by the front-end JSP, but rather the file uploaded to the files stored in the temporary folder under the private filename;
 File name//struts will automatically intercept the last file name injected to the attribute private String filefilename; Getter and setter at this time to save space @Override public String execute () throws Exception {//Save the path to the uploaded file string root = Servletact
  Ioncontext.getservletcontext (). Getrealpath ("/upload");
  Gets the temporary file input stream InputStream is = new FileInputStream (file);
  Output file OutputStream os = new FileOutputStream (new file (root, filefilename));
    Print out the filename of the uploaded file System.out.println ("Filefilename:" + filefilename);
  Since file is a file stored in a temporary folder, we can print its filename and file path to see if the filefilename is the same as before System.out.println ("file:" + file.getname ());

  System.out.println ("File:" + File.getpath ());
  byte[] buffer = new byte[1024];

  int length = 0;
  while ( -1!= (length = is.read (buffer, 0, buffer.length)) {os.write (buffer);
  } os.close ();

  Is.close ();
 return SUCCESS;

 }
}

First of all, we have to be clear that the file here is not really refer to the JSP uploaded files, when the file upload, Struts2 will first look for Struts.multipart.saveDir (this is in default.properties inside). The location specified by this name (default is null), we can specify this temporary file storage location in the struts2 of our project.

<constant name= "Struts.multipart.saveDir" value= "/repository"/>

If Struts.multipart.saveDir is not set, then the address specified by the Javax.servlet.context.tempdir is used by default, and the Javax.servlet.context.tempdir value is determined by the server, for example: if my The context of Web engineering is ABC, the server uses TOMCAT, then Savepath should be%tomcat_home%/work/catalina/localhost/abc_, the name of the temporary file is similar to upload__ 1a156008_1373a8615dd__8000_00000001.tmp, the temporary file name for each upload may be different, but this is roughly the style. And if you use servers in eclipse to configure TOMCAT and start, then the%tomcat_home% in the address above will not be the actual TOMCAT root in the system, but will be the address that eclipse gives it. For example, my local address is this:/home/wang/eclipsejavacode/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/catalina/ Localhost/abc/upload__1a156008_1373a8615dd__8000_00000001.tmp.

Struts2 complete the download.

Struts2 's file download is simpler by defining an input stream and then writing the file to the input stream, and the key configuration is configured in the Struts.xml configuration file:

public class Filedownloadaction extends Actionsupport
{
 //To download the file on the server path
 private String path;
 The file name to download is
 private String downloadfilename;
 Write getter and setter public
 InputStream getdownloadfile ()
 {
  return Servletactioncontext.getservletcontext (). getResourceAsStream (path);
 }

 @Override public
 String execute () throws Exception
 {
 //current action defaults to top
  of Valuestack stack Setdownloadfilename (XXX);
  Return SUCCESS
 }
}

The action simply defines an input stream downloadfile and then gives it a getter method, and then we look at the Struts.xml configuration file:

 <action name= "FileDownload" class= "com.struts2.FileDownloadAction" > <result name= "Download"
    Stream ">
  <param name=" contentdisposition ">attachment;filename=" ${downloadfilename} "</param>
  <param name= "InputName" >downloadFile</param>
   </result>
 </action>

Struts.xml configuration file There are a few places we should note that first is the type of result, types must be defined as stream type _, tell action this is the Result,result element of the file download, there are generally param child elements, This is used to set the file download parameters, InputName This property is to get the action of the file input stream, name must and action in the input stream attribute name, and then the Contentdisposition property, This property is generally used to specify what we want to do with the downloaded file, if the value is attachment, will pop up a download box, let the user choose whether to download, if not set this value, then the browser will first see if they can open the downloaded file, if you can, will open the downloaded file directly, (this is certainly not what we need), another value is filename, which is the file download name prompted by the file. After configuring this information, we will be able to implement the download function of the file.

SPRINGMVC Complete Upload:

The view is exactly the same in the struts2 example. This is not written out.

Controller:

@Controller
@RequestMapping (value= "fileoperate") public
class Fileoperateaction {
 @RequestMapping ( value= "upload") public
 String upload (httpservletrequest request, @RequestParam ("file") Multipartfile Photofile) {
 //Upload file to save the path
  String dir = request.getsession (). Getservletcontext (). Getrealpath ("/") + "upload";
  The original filename
  String filename = photofile.getoriginalfilename ();      Gets the file name extension
  String extname = filename.substring (Filename.lastindexof (".")); 
 Prevent file name conflicts, the name of a small change
 filename = filename.substring (0,filename.lastindexof (".")) + system.nanotime () + extname; 
  Fileutils.writebytearraytofile (New File (Dir,filename), photofile.getbytes ());
  Return "Success";
 }
 

SPRINGMVC Complete Download:

 @RequestMapping ("/download") public
 string Download (string fileName, httpservletrequest request,
   HttpServletResponse response) {
  response.setcharacterencoding ("Utf-8");
  Response.setcontenttype ("Multipart/form-data");
  Response.setheader ("Content-disposition", "attachment;filename="
    + fileName);
  try {
   InputStream inputstream = new FileInputStream (path to file);

   OutputStream OS = Response.getoutputstream ();
   Byte[] B = new byte[2048];
   int length;
   while (length = Inputstream.read (b)) > 0) {
    os.write (b, 0, length);
   }

    mainly off here.
   os.close ();

   Inputstream.close ();
  } catch (FileNotFoundException e) {
   e.printstacktrace ();
  } catch (IOException e) {
   e.printstacktrace (); c22/>}
   //Return value should be noted, or the following error will appear!
   //java+getoutputstream () has already been called for this response return
  null;
 }

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.