java附件下载乱码

public static final void downloadfile(HttpServletRequest request, HttpServletResponse response, String path, String fileName)
{
File downloadFile = null;
    File file =new File(path);
    //判断存在
    if(file.exists()){
    //为文件夹,下载文件夹内文件
    if(file.isDirectory()){
    String[] children = file.list();
    if(children!=null&&children.length>0)
    {
    downloadFile = new File(file, children[0]);
    }
    }
    else
    {
    downloadFile = file;
    }
    }
    if (downloadFile!=null && downloadFile.exists())
    {
    InputStream inputStream = null; 
    OutputStream outputStream = null;    
    // 以流的形式下载文件 
    try
    {
    inputStream = new BufferedInputStream( new FileInputStream(downloadFile)); 
    outputStream = new BufferedOutputStream(response.getOutputStream()); 
    byte[] buffer = new byte[inputStream.available()]; 
    inputStream.read(buffer); 
    response.reset();  // 清空response
    //设置response的Header 
    String userAgent = request.getHeader("User-Agent");
    //针对IE或者以IE为内核的浏览器:
    if (userAgent.contains("MSIE")||userAgent.contains("Trident"))
    {
    fileName = URLEncoder.encode(fileName, "UTF-8");
    }
    else
    {
    //非IE浏览器的处理:
    fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
    }
    response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setCharacterEncoding("UTF-8");
    response.addHeader("Content-Length", "" + downloadFile.length()); 
    response.setContentType("application/octet-stream"); 
    outputStream.write(buffer); 
    outputStream.flush(); 
    }
    catch (IOException e)
    {
    logger.error("名为:"+fileName+"的文件下载出错");
    }
    finally
    { 
    if(inputStream!=null){
    try
    {
    inputStream.close();
    }
    catch(IOException e)
    {
    logger.error("输入流关闭错误");
    e.printStackTrace();
    }
    }
    if(outputStream!=null){
    try
    {
    outputStream.close();
    }
    catch (IOException e)
    {
    logger.error("输出流关闭错误");
    e.printStackTrace();
    }
    }
    }  
    }
    else
    { 
      logger.error("文件不存在");
    }
}

猜你喜欢

转载自zhangboxiaoyao.iteye.com/blog/2337771
今日推荐