下载文件

前台

    var form=$("<form>");//定义一个form表单
    form.attr("style","display:none");
    form.attr("target","");
    form.attr("method","post");
    form.attr("action",contextPath + "/exportFile.do?file_name=" + encodeURI(encodeURI("赛程安排表.xls")) + "&oldName=" + encodeURI(encodeURI("赛程安排表.xls")));
    var input1=$("<input>");
    input1.attr("type","hidden");
    input1.attr("name","exportFile");
    input1.attr("value",(new Date()).getMilliseconds());
    form.append(input1);
    $("#uploadfile_div").append(form);//将表单放置在web中
    form.submit();//表单提交

在Spring 后台

public void exportFile(String file_name, String oldName, HttpSession session, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
        String fileName = java.net.URLDecoder.decode(file_name,"UTF8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");  
        response.setHeader("Content-Disposition", "attachment;fileName=" + new String(oldName.getBytes("GB2312"), "ISO_8859_1"));
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile");
        realPath = realPath.replace("\\", "/");
        try {  
            File file=new File(realPath+"/"+fileName);
            System.out.println(file.getAbsolutePath());  
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }

经测试,火狐和IE下都可以下载文件!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值