现在的位置: 首页 > 综合 > 正文

java文件下载及名称乱码问题

2013年12月18日 ⁄ 综合 ⁄ 共 2281字 ⁄ 字号 评论关闭

package com.wind.dairysystem.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;

import com.wind.dairysystem.dao.DBUtil;

public class ImportUserDairyToExcel extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setCharacterEncoding("utf-8");
//S流下载
resp.setContentType("application/octet-stream;charset=UTF-8"); 
//E流下载
String time = req.getParameter("time");
FileSystemView fsv = FileSystemView.getFileSystemView();
    String homePath = fsv.getHomeDirectory().getPath(); 
    String fileName = "";
    if(time != null)
fileName = "WWPI_成员日志统计结果."+time+".xls";
else
fileName = "WWPI_成员日志统计结果.xls";
    String retuName = new String(fileName.getBytes("utf-8"),"ISO8859_1");       

    fileName = homePath +"\\"+ fileName; 
    System.out.println(fileName);
        File excel = new File(fileName);
        String year = time.substring(0, 4);
        String mouth = time.substring(5,7);
        DBUtil db = new DBUtil();
        try {
        db.importUserDairyToExcel(excel, year, mouth);
        }catch(Exception e){
        e.printStackTrace();
        }

//STest
// 写流文件到前端浏览器
   ServletOutputStream out = resp.getOutputStream();
   System.out.println("retuName:" + retuName);
   resp.reset();   
   resp.addHeader("Content-Disposition", "attachment; filename=" + retuName);  
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   try {
     bis = new BufferedInputStream(new FileInputStream(fileName));
     bos = new BufferedOutputStream(out);
     byte[] buff = new byte[2048];
     int bytesRead;
     while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
       bos.write(buff, 0, bytesRead);
     }
   } catch (IOException e) {
     throw e;
   } finally {
     if (bis != null)
       bis.close();
     if (bos != null)
       bos.close();
   }
   excel.delete();
//ETest
        //resp.getWriter().print("生成成功!");
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
}

}

ext前端:

window.open("importUserDairyToExcel?time="+time);

抱歉!评论已关闭.