日期:2014-05-16  浏览次数:20322 次

jsp 下载文件
<%@page language="java" import="java.io.*,java.net.*"
pageEncoding="gb2312"%>

<%
String filePath = (String) request.getParameter("filePath");
String fileName = (String) request.getParameter("fileName");
fileName="book_vnet.swf";
response.reset();
response.setContentType("application/x-download");
String filenamedownload = filePath;
String filenamedisplay = fileName;
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
URL url = null;
HttpURLConnection conn = null;

try {
url = new URL(filenamedownload);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
conn.setRequestMethod("POST");
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

conn.setUseCaches(false);

conn.setAllowUserInteraction(true);
InputStream fis = null;
OutputStream output = null;
try {
output = response.getOutputStream();
fis = conn.getInputStream();

byte[] b = new byte[1024];
int i = 0;

while ((i = fis.read(b)) > 0) {
output.write(b, 0, i);
}
output.flush();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
fis = null;
}
if (output != null) {
output.close();
output = null;
}
}
%>