SpringMVC 文本文件下载的配置

页面:

 <fieldset>
     <legend>Download annotator list</legend>
     <img src="pages/tools/listannotator/img/text.png" id="downloadAnnotatorListCsvImg"/>&nbsp;
     <img src="pages/tools/listannotator/img/xls.png"/>
 </fieldset>

 

JS代码:

$("#downloadAnnotatorListCsvImg").click(
        function(){
            var wnd=openCenterWindow(APP_NAME+"downloadAnnotatorListCsv.html","Download Annotator List in CSV format",400,300);
        }
    );


var APP_NAME="/rttsbiz2/";

function openCenterWindow(url,windowName,width,height){
    var left = (window.screen.availWidth-10-width)/2;     
    var top = (window.screen.availHeight-30-height)/2;       
      
    var wnd=window.open(url,windowName,"height="+height+",width="+width+",top="+top+",left="+left+",resizable=yes,scrollbars=yes,status=no,location=no,");
    return wnd;
}

 

Controller代码:

@RequestMapping("/downloadAnnotatorListCsv")
    public ModelAndView download(HttpServletRequest request,HttpServletResponse response){

        
        String fileName="download-single.txt";
        
        response.reset();// 不加这一句的话会出现下载错误 
        response.setHeader("Content-disposition", "attachment; filename="+fileName);// 设定输出文件头   
        response.setContentType("text/x-plain");// 定义输出类型 
        
        try {
            ServletOutputStream out = response.getOutputStream();
            
            String path = System.getProperty("java.io.tmpdir") + "\\poem.txt";
            File file = new File(path);
            FileOutputStream fos = new FileOutputStream(file);   
            Writer writer = new OutputStreamWriter(fos, "utf-8");   
            
            String text="Hello!download!";
            writer.write(text);   
            writer.close();   
            fos.close();  
            
            FileInputStream fis = new java.io.FileInputStream(file);
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096);
            
            byte[] cache = new byte[4096];
            for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) {
                    byteOutputStream.write(cache, 0, offset);
            }
            
            byte[] bt = null;
            bt = byteOutputStream.toByteArray();               
            
            out.write(bt);
            out.flush();
            out.close();
            fis.close();
            if(file.exists()){
                file.delete();
            }            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        return null;
    }
}

只是记录一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值