Java implementation file breakpoint download function _java

Source: Internet
Author: User
Tags ranges trim stringbuffer

The example of this article for everyone to share the Java Breakpoint download code for your reference, the specific content as follows

1. Java code

Implementation file Download function public String downloadFile () {File dir = new file (filepath);//Get File Lu Jin if (!dir.exists ()) {Syste
      M.out.println ("File path error");
      Log.debug ("File path error"); Return "failed"//To determine whether a file or folder exists} file DownloadFile = new file (dir, filename);//Find files in the specified directory if (!downloadfile.
        Isfile ()) {System.out.println ("file does not exist");
        Log.debug ("File does not exist");
     Return "failed";//determine if a file or folder exists} try {downloadfileranges (downloadFile);
       catch (Clientabortexception e) {System.out.println ("connection terminated");
     Log.debug ("Connection terminated");
     catch (IOException e) {e.printstacktrace ();
   return null; } private void Downloadfileranges (DownloadFile) throws IOException {//File size to download long filelength = do
     Wnloadfile.length ();
     Downloaded file size long pastlength = 0;
     Whether the express download, otherwise for the Thunderbolt or other Boolean isflashget = true;
     Used to record the number of end bytes that need to be downloaded (thunder or other downloads) long lenend = 0; Used to record a string of data range strings rang the client requires downloadingEbytes = Request.getheader ("Range");
     For random Read Write file randomaccessfile RAF = NULL;
     OutputStream OS = null;
     OutputStream outPut = null;
     byte b[] = new byte[1024]; If the client download request contains a range if (null!= rangebytes) {//Return code 206 Response.setstatus (httpservletresponse.sc_p
      Artial_content);
      Rangebytes = Request.getheader ("Range"). ReplaceAll ("bytes=", ""); Determines the Range string pattern if (rangebytes.indexof ('-') = = Rangebytes.length ()-1) {//No end byte, for Express ISFLASHG
      ET = true;
      rangebytes = rangebytes.substring (0, Rangebytes.indexof ('-'));
      Pastlength = Long.parselong (Rangebytes.trim ());
      else {//Thunder Download Isflashget = false;
      String startbytes = rangebytes.substring (0, Rangebytes.indexof ('-'));
      String endbytes = rangebytes.substring (Rangebytes.indexof ('-') + 1, rangebytes.length ());
      Downloaded file Segment pastlength = Long.parselong (Startbytes.trim ()); Also need to download theNumber of bytes of file (starting from the downloaded file segment) Lenend = Long.parselong (endbytes);
     }//Notifies the client to allow a breakpoint to be transmitted, in response format: Accept-ranges:bytes response.setheader ("accept-ranges", "bytes");
     Response.reset ();  If the status defaults to 200 for the first download, the response format is: http/1.1 OK if (0!= pastlength) {//Content range string String contentrange =
      ""; Response Format//content-range:bytes [File Block start byte]-[Total size of file-1]| | [Total size of file] if (isflashget) {contentrange = new StringBuffer ("bytes"). Append (new Long (pastlength). ToString ()). Append ("-"). Append (New Long (fileLength-1). toString ()). Append ("/"). Append (New Long (filelength
      ). ToString ()). ToString (); else {contentrange = new StringBuffer (rangebytes). Append ("/"). Append (new Long (filelength). ToS
      Tring ()). ToString ();
     } response.setheader ("Content-range", Contentrange);
     String filename = getdownloadchinesefilename (filename); Response.setheader ("Content-dispositiOn "," attachment;filename= "+ filename +" ");
     The format of the response is: Response.setcontenttype ("Application/octet-stream");
     Response.AddHeader ("Content-length", String.valueof (Filelength));
      try {os = Response.getoutputstream ();
      OutPut = new Bufferedoutputstream (OS);
      RAF = new Randomaccessfile (DownloadFile, "R");
      Skip downloaded bytes raf.seek (pastlength);
      if (isflashget) {//express train etc int n = 0;
      while ((n = raf.read (b, 0, 1024))!=-1) {output.write (b, 0, N); } else {//Thunder wait while (Raf.getfilepointer () < Lenend) {Output.write (RAF).
      Read ());
     } output.flush (); catch (IOException e) {/** * When writing data for exceptions like Clientabortexception * Because the client canceled the download and the server side continued to browse This exception is thrown when the device writes the data, which is normal.
      Especially for the thunder of this blood-sucking client software. * Clearly there is already a thread in the read bytes=1275856879-1275877358, * If the short time did not read, the Thunderbolt will restart the second, the third ... Thread reads the same byte segment until a thread is read, and the Thunderbolt Kill * Off others are downloading the same byte segment of the thread, forcibly aborted byte read out, causing the server to throw clientabortexception.
      * So, we ignore this exception */} finally {if (OutPut!= null) {output.close ();
      } if (RAF!= null) {raf.close (); }} private String Getdownloadchinesefilename (String paramname) {string Downloadchinesef
   Ilename = "";
   try {downloadchinesefilename = new String (paramname.getbytes ("GBK"), "iso8859-1");
   catch (Unsupportedencodingexception e) {e.printstacktrace ();
   return downloadchinesefilename;
  Public String GetFilePath () {return filepath;
  } public void SetFilePath (String filepath) {this.filepath = filepath;
  Public String GetFileName () {return filename;
  public void Setfilename (String filename) {this.filename = filename;
   Public HttpServletRequest Getrequest () {return request;
 Public HttpServletResponse GetResponse () {  return response; }

2. Struts Section

Copy Code code as follows:
<action name= "DownloadFile" class= "downloadfileaction" method= "DownloadFile" >
<result name= "Failed" type= "Redirectaction" >showDownloadFileNameList</result>
</action>

3. JSP part

Copy Code code as follows:
<td><a href= "Downloadfile?filename=${filemap.key}&&filepath=${filemap.value}" > File download </a ></td>

Related Article

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.