import java.io.File;
import
java.io.FileInputStream;
import java.io.IOException;
import
java.io.OutputStream;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
public class DownloadAction
{
//要從服務器下載的方法
public void
getFile(HttpServletRequest request,HttpServletResponse response) throws
IOException{
String
file_name=request.getParameter("file_name"); //要下載的文件名
if(file_name==null){file_name="";}
String
realpath=request.getSession().getServletContext().getRealPath("/");//獲取服務器的物理路徑
String temp1 = File.separator;//路徑分隔符("//")
String
filedownload_url=realpath+"temp"+temp1+file_name;//要提供下載的文件的物理路徑+文件名
System.out.println("filedownload="+filedownload_url);
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=/""+file_name+"/"");
//新建文件輸入輸出流
OutputStream
output = null;
FileInputStream fis =
null;
try{
File f =
new File(filedownload_url);//新建File對象
output =
response.getOutputStream();//新建文件輸入輸出流對象
fis = new
FileInputStream(f);
byte[] b = new
byte[(int)f.length()]; //設置每次寫入緩存大小
//把輸出流寫入客戶端
int i = 0;
while((i =
fis.read(b)) > 0){
output.write(b, 0,
i);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
if(fis
!= null)
{
fis.close();
fis =
null;
}
if(output !=
null)
{
output.close();
output =
null;
}
}
}
}