您的位置:首页 > 编程语言 > Java开发

springmvc实现浏览器下载文件

2016-07-14 10:42 477 查看
import org.springframework.util.FileCopyUtils;

/**

* 下载Excel
* @param request
* @param response
* @throws IOException
*/

 public static byte[] getBytes(String filePath){  

        byte[] buffer = null;  

        try {  

            File file = new File(filePath);  

            FileInputStream fis = new FileInputStream(file);  

            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  

            byte[] b = new byte[1000];  

            int n;  

            while ((n = fis.read(b)) != -1) {  

                bos.write(b, 0, n);  

            }  

            fis.close();  

            bos.close();  

            buffer = bos.toByteArray();  

        } catch (FileNotFoundException e) {  

            e.printStackTrace();  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

        return buffer;  

    }

@RequestMapping("download")
public void download(HttpServletRequest request,HttpServletResponse response) throws IOException {
String time  = request.getParameter("time");
String path = BaseUtil.readValue("PAYMENTORDER_EXCEL_BAK")+ "/收费记录_"+time+".xlsx";// 生成Excel的文件地址
String fileNameStr = "收费记录_"+time+".xlsx";
String fileName = new String(fileNameStr.getBytes("UTF-8"),"iso-8859-1");// 为了解决中文名称乱码问题
response.setContentType("application/x-msdownload");  
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename=\""+ fileName + "\"");
FileCopyUtils.copy(getBytes(path),response.getOutputStream());

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