Package com.yqcf.util;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Downfile {
/**
*
* Call Filedown (request,response) URL parameter on JSP page: Dirpath (full path of file), filename (filename)
*
* @return Boolean
*/
public boolean Filedown (HttpServletRequest request,
HttpServletResponse response) {
Gets the path and filename of the file ***************//
String Dirpath = Request.getparameter ("Dirpath");
String filename = request.getparameter ("FileName");
Determine if a file exists ********************//
File File = new file (Dirpath, fileName);
if (!file.exists ()) {
System.out.println ("File download failed: File or path error");
return false;
}
Long filelength = File.length ();
String length = string.valueof (filelength);
Sets the type and header information of the returned file, Application/octet-stream: Common format for file types//
Response.setcontenttype ("Application/octet-stream");
Response.setheader ("Content-disposition", "Attachment;filename="
+ FileName);
Response.setheader ("Content_length", Length);
FileInputStream input = null;
Servletoutputstream output = null;
try {
Generate input stream and output stream *************//
input = new FileInputStream (file);
Output = Response.getoutputstream ();
byte[] block = new byte[1024];
int len = 0;
Start Download File *****************//
while (len = input.read (block))! =-1) {
Output.write (block, 0, Len);
}
Output.flush ();
return true;
} catch (IOException e) {
System.out.println ("File download failed:" + e.getmessage ());
return false;
} finally {
Close file Stream ****************//
try {
if (input! = null) {
Input.close ();
}
if (output! = null) {
Output.close ();
}
} catch (IOException ex) {
System.out.println (Ex.getmessage ());
}
}
}
}
HTTP download file (common format). JSP J Ava