Blog originated from: http://www.jb51.net/article/43913.htm
-----------------------
Public httpservletresponse Download (String path, httpservletresponse response) {try {
Path refers to the paths of files that you want to download.
File File = new file (path);
Gets the file name.
String filename = File.getname ();
Gets the suffix name of the file.
String ext = filename.substring (Filename.lastindexof (".") + 1). toUpperCase ();
Download the file as a stream.
InputStream fis = new Bufferedinputstream (new FileInputStream (path));
byte[] buffer = new byte[fis.available ()];
Fis.read (buffer);
Fis.close ();
Empty response
Response.reset ();
Set header for response
Response.AddHeader ("Content-disposition", "attachment;filename=" + New String (Filename.getbytes ());
Response.AddHeader ("Content-length", "" "+ File.length ());
OutputStream toclient = new Bufferedoutputstream (Response.getoutputstream ());
Response.setcontenttype ("Application/octet-stream");
Toclient.write (buffer);
Toclient.flush ();
Toclient.close ();
catch (IOException ex) {
Ex.printstacktrace ();
}
return response;
}
public void downloadlocal (HttpServletResponse response) throws FileNotFoundException {
Download Local Files
String fileName = "Operator.doc". toString (); Default save name for file
Read in the stream
InputStream instream = new FileInputStream ("C:/operator.doc")//File storage path
Format the output
Response.reset ();
Response.setcontenttype ("bin");
Response.AddHeader ("Content-disposition", "attachment; Filename=\ "" + fileName + "\");
Loop out the data in the stream
Byte[] B = new byte[100];
int Len;
try {
while (len = Instream.read (b)) > 0)
Response.getoutputstream (). Write (b, 0, Len);
Instream.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
public void Downloadnet (HttpServletResponse response) throws Malformedurlexception {
Download network files
int bytesum = 0;
int byteread = 0;
URL url = new URL ("Windine.blogdriver.com/logo.gif");
try {
URLConnection conn = Url.openconnection ();
InputStream instream = Conn.getinputstream ();
FileOutputStream fs = new FileOutputStream ("C:/abc.gif");
byte[] buffer = new byte[1204];
int length;
while ((Byteread = instream.read (buffer))!=-1) {
Bytesum + = Byteread;
System.out.println (bytesum);
Fs.write (buffer, 0, byteread);
}
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
}