2013年11月2日星期六

JAVA WEB downloaded files with a servlet can not pop-up dialog


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String filename = request.getParameter("filename");
String filepath = sc.getRealPath("/") + savePath + "\\" + filename;
//创建要下载的文件的对象(参数为要下载的文件在服务器上的路径)
        File serverFile=new File(filepath);
        //设置要显示在保存窗口的文件名,如果文件名中有中文的话,则要设置字符集,否则会出现乱码。另外,要写上文件后缀名  
        String fileName=java.net.URLEncoder.encode(filename,"utf-8");  
        //该步是最关键的一步,使用setHeader()方法弹出"是否要保存"的对话框,打引号的部分都是固定的值,不要改变  
        
        response.setHeader("Content-Disposition","attachment;filename="+fileName);  
        
        /* 
         * 以下四行代码经测试似乎可有可无,可能是我测试的文件太小或者其他什么原因。。。 
         */  
          
        //定义下载文件的长度 /字节  
        long fileLength=serverFile.length();  
        //把长整形的文件长度转换为字符串  
        String length=String.valueOf(fileLength);  
        //设置文件长度(如果是Post请求,则这步不可少)  
        response.setContentType("application/msword");
        response.setHeader("content_Length",length);  
          
        /* 
         *以上内容仅是下载一个空文件 
         *以下内容用于将服务器中相应的文件内容以流的形式写入到该空文件中 
         */  
        //获得一个 ServletOutputStream(向客户端发送二进制数据的输出流)对象  
        OutputStream servletOutPutStream=response.getOutputStream();  
        //获得一个从服务器上的文件myFile中获得输入字节的输入流对象  
        FileInputStream fileInputStream=new FileInputStream(serverFile);  
        byte bytes[]=new byte[1024];//设置缓冲区为1024个字节,即1KB  
        int len=0;  
        //读取数据。返回值为读入缓冲区的字节总数,如果到达文件末尾,则返回-1  
        while((len=fileInputStream.read(bytes))!=-1)  
        {     
            //将指定 byte数组中从下标 0 开始的 len个字节写入此文件输出流,(即读了多少就写入多少)  
            servletOutPutStream.write(bytes,0,len);   
        }  
          
        servletOutPutStream.close();  
        fileInputStream.close();
}

beg God to help me see what the big problem is not where the wrong ah
------ Solution - -------------------------------------------

this . . . Looks like or not , is not there any detail front did not notice ?  


landlord is using ajax submit it, can not be submitted using ajax Oh , only with a similar kind of
--- window.location.href --- For reference only ---------------------------------------
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName) + "\"");
Try
------ For reference only ----------------------------------- ----
lz try with the following code ,
following code on the computer and then all you can use a variety of browsers , and download the output file name can be Chinese
android mobile browser in use , looks like a problem
/**
 * 下载
 * @param filePath 文件路径(物理路径)
 * @param fileName 输出的文件名
 */
public static void downLoad(String filePath, String fileName) {
downLoad(new File(filePath), fileName);
}

/**
 * 下载
 * @param file 文件
 * @param fileName 输出的文件名
 */
public static void downLoad(File file, String fileName) {
try {
if (file.exists() && file.isFile()) {
downLoad(new FileInputStream(file), fileName, file.length());
}
} catch (Exception e) {
log.error("下载", e);
throw new MvcException(e.getMessage());
}
}

/**
 * 下载
 * @param input 输入流
 * @param fileName 输出的文件名
 * @param fileSize 文件大小
 */
public static void downLoad(InputStream input, String fileName, long fileSize) {
try {
HttpServletResponse response = HttpThread.getResponse();// 线程池中取出response
String agent = HttpThread.getRequest().getHeader("USER-AGENT").toLowerCase();
String name = new String(fileName.getBytes(agent.indexOf("msie") != -1 ? "GBK" : CharEncoding.UTF_8), CharEncoding.ISO_8859_1);
response.setHeader("Content-disposition", "attachment;filename=" + name);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", "" + fileSize);
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[1024];int i = 0;
while ((i = input.read(buffer)) != -1) {
output.write(buffer, 0, i);
}
input.close();output.flush();output.close();
} catch (Exception e) {
log.error("下载", e);
}
}

------ For reference only ----------------------------------- ----

looks like or not
------ For reference only ---------------------------------------

this . . . Looks like or not , is not there any detail front did not notice ?
------ For reference only -------------------------------------- -
plus one : response.setContentType ("application / x-download");
------ For reference only ---------------- -----------------------
then the problem may be your front-end

    BufferedInputStream bi = new BufferedInputStream(new FileInputStream(tempFileName));   
    OutputStream os = response.getOutputStream();    
    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    response.setContentType("application/x-msdownload");
byte buffer[] = new byte[1024];  
int size;  
while ((size = bi.read(buffer, 0, buffer.length)) != -1) {
os.write(buffer, 0, size);
}
    bi.close();
    os.close();

------ For reference only ----------------------------------- ----

this . . . Looks like or not , is not there any detail front did not notice ?          
  
  
landlord is using ajax submit it, can not be submitted using ajax Oh , only with a similar kind of window.location.href  
positive solution, I use the ajax submitted after the submission of the successful completion of change window.location.href

没有评论:

发表评论