前台ajax请求后台实现下载

来源:互联网 发布:java xml生成pdf 编辑:程序博客网 时间:2024/05/17 05:14

下面是大致代码。

jsp页面:

function getDada(){

       var returnFilePath = "";

        ....

         ...

$.ajax({
            url: "a/b",
            data: {data1: data1,data2: data2,},
            type: "post",
            async: false,   // 必须同步
            success: function (data) {
            returnFilePath = data;
            }
        });
        return returnFilePath;

}


要在后台实现下载页面需要增加一个函数:

function getDada() {
var filePath = getDada();
window.location.href = "a/c?filePath="+encodeURI(encodeURI(filePath));
}


java后台:

       //  创建文件

       @RequestMapping("/getDada")
public void getDada(String data1,String data2,HttpServletRequest request,HttpServletResponse response) throws Exception{

        .....

        .....

        try {  
            
        String fileTime = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date().getTime());
        String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\note.sql";
               System.out.println("filePath==="+filePath);  
File f = new File(filePath);  
              if (f.exists()) {  
                System.out.print("文件存在");  
              } else {  
                System.out.print("文件不存在");  
                f.createNewFile();// 不存在则创建  
             }  
            str = sb.toString();
  
            BufferedWriter output = new BufferedWriter(new FileWriter(f));  
            output.write(str);  
            output.close();  


    response.getWriter().write(filePath);         // 将路径返回到页面,即ajax请求返回的结果
   
        } catch (Exception e) {  
            e.printStackTrace(); 
        }

       }

       


        // 下载

@RequestMapping("/downloadFile")
         public static void download(String filePath, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
filePath = URLDecoder.decode(request.getParameter("filePath"), "UTF-8");
String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
response.reset();
response.setContentType("application/octet-stream");  
//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));

BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileInputStream fis = null;
OutputStream fos = null;  
File fPath = new File(filePath);
        try { 
            if (fPath.exists()) {  
            fis = new FileInputStream(filePath);
                bis = new BufferedInputStream(fis);
                fos = response.getOutputStream();
                bos = new BufferedOutputStream(fos);
                int bytesRead = 0;
                byte[] buffer = new byte[5 * 1024];
                while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                }
            } else {  
                System.out.print("文件不存在");
            } 
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if (bos != null) {
                    bos.close();
                }
                if(fos != null){
                fos.close();
                }
                if(bis != null){
                bis.close();
                }
                if(fis != null){
                fis.close();
                }
                // 下载完成后删除服务器上的原文件
                fPath.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


0 0