废话不多说
注意:不能用ajax下载哈,需要用页面请求!
public void download() throws IOException {
String filepath = request.getParameter("downurl");//这个是文件的路径
String fullFilePath = ServletActionContext.getServletContext()
.getRealPath(filepath);
/* 读取文件 */
File file = new File(fullFilePath);
/* 如果文件存在 */
try {
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), "utf-8");
response.reset();
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/* 如果文件长度大于0 */
if (fileLength != 0) {
/* 创建输入流 */
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
/* 创建输出流 */
ServletOutputStream servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这个下载是基于servlet实现的。用这种下载文件好些,比晓得地址直接就链接过去。因为这样我只是可以判断用户是否登录或者有没权限什么的