Java code to implement file downloads

Source: Internet
Author: User
Tags http post

Java code to implement file downloads


This is the implementation download class (servlet), with detailed idea codes such as the following:
You can also connect to a database
Package com.message;

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;

public class Filedownservlet extends HttpServlet {
private static final String Content_Type = "text/html; CHARSET=GBK ";

Initialize Global Variables
public void Init () throws Servletexception {
}

Process the HTTP Get request
public 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 Chinese garbled problem
String Filename=new string (request.getparameter ("filename"). GetBytes ("Iso-8859-1"), "GBK");

Create a File object
File File=new file ("f://book//webroot//" +filename);

To set the encoding for response
Response.setcontenttype ("Application/x-msdownload");

Specify the size of the file to download
Response.setcontentlength ((int) file.length ());

Set additional file names
Response.setheader ("Content-disposition", "attachment;filename=" +filename);

Solve Chinese garbled characters
Response.setheader ("Content-disposition", "Attachment;filename=" +new String

(Filename.getbytes ("GBK"), "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];//equivalent to our cache

Long k=0;//This value is used to calculate how many bytes are currently actually downloaded

Get the output stream from the response object, ready to download

OutputStream Myout=response.getoutputstream ();

Start cycle 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);

}

Data that is written to the client's memory, flushed to disk
Myout.flush ();

}

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

Clean up resources
public void Destroy () {
}
}

This is the JavaBean, the main implementation and database connection, assuming that there is no database connection, you can directly do not this
Package com;

public class Messagebean {
Private String Message;

Public String GetMessage () {
return Message;
}

public void Setmessage (String message) {
message = message;
}
}


HTML page load write, or connect to database (case code also in)
<%@ page language= "java" import= "java.util.*,com.message.*" pageencoding= "GBK"%>
<jsp:directive.page import= "com. Messagebean; " />
<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >

<title>my JSP ' book.jsp ' starting page</title>

<meta http-equiv= "Pragma" content= "No-cache" >
<meta http-equiv= "Cache-control" content= "No-cache" >
<meta http-equiv= "Expires" content= "0" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
<meta http-equiv= "description" content= "This is my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-


<body>
<!--<a href= "Java.rar" >5.1 download book--java</a> <br>-->
<%
Vector vv= (vector) session.getattribute ("message");
for (int i=0;i<vv.size (); i++) {
Messagesbean mb= (Messagesbean) vv.get (i);
Out.println ("<tr>");
Out.println ("<td>" +mb.getsender () + "</td>");
Out.println ("<td>" +mb.getmess_time () + "</td>");
Out.println ("<td>" +mb.getgeter () + "</td>");
Out.println ("<td>" +mb.getmess_content () + "</td>");
String Filename=null;
Session.setattribute ("Java.rar", filename);
Get file name
Filename=getfilepath (). substring (Mb.getfilepath (). LastIndexOf ("/") +1);
Out.println ("<td><a href=filedownservlet?filename=java.rar>5.1 download book--java</a></td>");// Java.rar This can be changed into a variable
Out.println ("<td><a href=filedownservlet?filename=dos.rar>dos video tutorial </a></td>");
Out.println ("<td><a href=filedownservlet?filename= often use DOS commands to .rar> frequently using DOS command </a></td>");
Out.println ("</tr>");
// }
%>
</body>


//This is the Web. XML configuration file, which is very important, otherwise it is very difficult to implement OH
<?xml version= "1.0" encoding= "UTF-8"?
<web-app version= " 2.4 "
 xmlns=" http://java.sun.com/xml/ns/j2ee "
 xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "
 xsi:schemalocation=" HTTP://JAVA.SUN.COM/XML/NS/J2EE
 http://java.sun.com/ Xml/ns/j2ee/web-app_2_4.xsd
  <servlet>
    <description>this is the Description of my EE component</description>
    <display-name>this is the display name of my EE component</display-name>
    <servlet-name>filedownservlet</ Servlet-name>
    <servlet-class>com.message.FileDownServlet</servlet-class>
  </servlet>

<servlet-mapping>
<servlet-name>FileDownServlet</servlet-name>
<url-pattern>/FileDownServlet</url-pattern>
</servlet-mapping>
</web-app>

Java code to implement file downloads

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.