下载文件后如何使用response.setContentType(“APPLICATION / DOWNLOAD”)获取响应

时间:2013-01-31 10:59:32

标签: java jsp

我想从ajax调用得到响应我正在制作一个jsp页面。这个jsp页面下载了该文件。但下载后它不会将控制权返回给ajax调用。执行in.close()后; os.close();控制丢失的线路 它提示下载文件。在下载文件时,控件丢失。这是我的代码

    <%@page import="Encryption.decryptCaesar"%>
    <%@page import="java.io.File"%>
    <%@page import="java.io.FileInputStream"%>
    <%@page import="java.io.OutputStream"%>
    <%@ page trimDirectiveWhitespaces="true" %>
    <%
    try
     {

    String Name =(String) request.getParameter("Name");
    String EmailID =(String) request.getParameter("EmailID");
    String ContactNumber =(String) request.getParameter("ContactNumber");
    String Text =(String) request.getParameter("Message");
    String shiftKey=(String) request.getParameter("shiftKey");
    String FileName=(String) request.getParameter("FileName");
    System.out.println(FileName);
    String data=null;
    String fileName="/home/maclean/SecureCloud/"+FileName;
    File file = new File(fileName);
    FileInputStream in = new FileInputStream(file);
    OutputStream os = response.getOutputStream(); 

    response.setContentType("APPLICATION/DOWNLOAD");

                response.setContentLength(in.available());
                int length;
                byte[] buffer = new byte[4096];

                   while ((length = in.read(buffer)) > 0){
                         data=new String(buffer);
                      buffer =decryptCaesar.Decrypt(data,shiftKey).getBytes();
        os.write(buffer, 0, buffer.length);
        System.out.println(buffer);
    }

    os.write(("OK").getBytes());
    response.setHeader("Content-Disposition", "attachment"+ "filename=" +fileName);
                in.close();
                os.close();
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write("OK"); 

    response.flushBuffer();


    } catch(Exception e)
                   {
               response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write("NOTOK"); 
    response.flushBuffer();
        e.printStackTrace();
    }


    %>

0 个答案:

没有答案