首页 > 代码库 > http下载文件(通用格式) .jsp j ava
http下载文件(通用格式) .jsp j ava
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 {
/**
*
* 在jsp页面调用fileDown(request,response) url传参:dirPath(文件的全路径),fileName(文件名)
*
* @return boolean
*/
public boolean fileDown(HttpServletRequest request,
HttpServletResponse response) {
// ************取得文件的路径和文件名***************//
String dirPath = request.getParameter("dirPath");
String fileName = request.getParameter("fileName");
// ************判断文件是否存在********************//
File file = new File(dirPath, fileName);
if (!file.exists()) {
System.out.println("文件下载失败:文件或路径错误");
return false;
}
long fileLength = file.length();
String length = String.valueOf(fileLength);
// 设置返回文件的类型和头信息,application/octet-stream:文件类型的通用格式//
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileName);
response.setHeader("Content_Length", length);
FileInputStream input = null;
ServletOutputStream output = null;
try {
// **************产生输入流和输出流*************//
input = new FileInputStream(file);
output = response.getOutputStream();
byte[] block = new byte[1024];
int len = 0;
// **************开始下载文件*****************//
while ((len = input.read(block)) != -1) {
output.write(block, 0, len);
}
output.flush();
return true;
} catch (IOException e) {
System.out.println("文件下载失败:" + e.getMessage());
return false;
} finally {
// *************关闭文件流****************//
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
http下载文件(通用格式) .jsp j ava