0
我編寫了一個啓動文件下載的servlet。該文件的數據在客戶端的請求中收到。它適用於Chrome瀏覽器,但不適用於Firefox。這是什麼原因? Firefox的處理下載與其他瀏覽器不同嗎?使用Firefox下載Servlet文件
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();
}
請展開「不工作」部分。調試一個問題的近似是非常困難的...... –
在IE瀏覽器中,Chrome瀏覽器和Safari瀏覽器的下載會顯示正確的名稱和數據,但不會顯示在Firefox中。 – Zicane
這是可見的後果,但它不會幫助您調試錯誤。在這裏發佈相關的源代碼和任何其他有用的信息。 –