使用Firefox下载Servlet文件

时间:2014-01-19 21:51:59

标签: java google-app-engine gwt

我编写了一个启动文件下载的servlet。在客户端的请求中接收文件的数据。它适用于,即chrome和amp; safari,但不是在Firefox中。这是什么原因? firefox处理下载是否与其他浏览器不同?

private static final int BUFFER_SIZE = 4096; 
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String before = req.getReader().readLine();
    String filename = "";
    String content = "";

    if(before == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data received!");
        return;
    } else {        
        String decoded = URLDecoder.decode(before, "UTF-8");
        {
            int i = 0;
            StringTokenizer tokenizer = new StringTokenizer(decoded, "\n");
            while (tokenizer.hasMoreTokens()) {
                if(i == 0) {
                    filename += tokenizer.nextToken();
                } else {
                    content += tokenizer.nextToken();
                }
                i++;
            }
        }           
        filename = filename.replace("hidden=", "").replace("\n", "").replace("\r", "");
    }

    ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes()); 
    int fileLength = inputStream.available(); 

    ServletContext context = getServletContext();

    // sets MIME type for the file download
    String mimeType = context.getMimeType(filename);
    if (mimeType == null) {        
        mimeType = "application/octet-stream";
    }              

    // set content properties and header attributes for the response
    resp.setContentType(mimeType);
    resp.setContentLength(fileLength);
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", filename);
    resp.setHeader(headerKey, headerValue);

    // writes the file to the client
    OutputStream outStream = resp.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close(); 
}

1 个答案:

答案 0 :(得分:0)

如果您希望浏览器始终显示下载对话框(而不是尝试打开文件本身),请尝试将内容类型强制为application/octet-stream,而不是根据文件类型进行设置。

换句话说,尝试替换这些行:

ServletContext context = getServletContext();

// sets MIME type for the file download
String mimeType = context.getMimeType(filename);
if (mimeType == null) {        
    mimeType = "application/octet-stream";
}              

// set content properties and header attributes for the response
resp.setContentType(mimeType);

这一个:

resp.setContentType("application/octet-stream");

我不知道你是如何触发下载的,但是如果你使用隐藏的框架,我的猜测是Firefox试图直接在隐藏框架中打开文件,因为它识别文件类型。