您的位置:首页 > 其它

文件下载功能

2015-09-20 13:28 295 查看
public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

OutputStream os = null;

InputStream is = null;

String filename=request.getParameter("filename");

//String filename2 = new String(filename.getBytes("UTF-8"),"iso-8859-1");

filename = new String(filename.getBytes("iso8859-1"),"UTF-8");

// filename= URLEncoder.encode(filename, "UTF-8");

// filename= URLDecoder.decode(filename,"UTF-8");

System.out.println(">>>>>>>>filename>"+filename);

String filePath = request.getSession().getServletContext().getRealPath("/myread/" + filename);//项目路径

File downloadFile = new File(filePath);

is = new FileInputStream(downloadFile);

bis = new BufferedInputStream(is);

os = response.getOutputStream();

bos = new BufferedOutputStream(os);

// request.setCharacterEncoding("iso-8859-1");

String fileName = java.net.URLEncoder.encode(filename, "UTF-8");//处理中文文件名的问题

// fileName = new String(fileName.getBytes("UTF-8"),"gbk");//处理中文文件名的问题

// System.out.println(">>>>>>>>fileName==>"+fileName);

response.reset();

response.setCharacterEncoding("utf-8");

response.setContentType("application/octet-stream");//文件类型contenttype

response.setHeader("Content-Disposition","attachment; filename=" + fileName); //关键部分,打开一个下载框

int bytesRead = 0;

byte[] buffer = new byte[8192];

while((bytesRead = bis.read(buffer,0,8192)) != -1)

{

bos.write(buffer, 0, bytesRead);

}

bos.flush();

is.close();

bis.close();

os.close();

bos.close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: