java中下載下傳檔案最好用servlet,我在用普通的類實作下載下傳功能時提示getOutputStream has already been commit 的error,查了好多資料都沒有解決,(有的說response要reset,有的說jsp頁面中不能換行等等,我試過後都不行)用servlet來做則不會有這個問題,源代碼如下:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = (String) request.getParameter("fileName");
String path = "/dept/hr/files/training/" + fileName;
String realPath = this.getServletContext().getRealPath(path);
File f = new File(realPath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
fileName = new String(fileName.getBytes("GB2312"), "ISO8859_1"); //處理檔案中含中文的問題,不是萬能的
boolean isOnLine = false;
response.reset(); //非常重要
if (isOnLine) { //線上打開方式
URL u = new URL("file:///" + realPath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition",
"inline; filename=" + f.getName());
} else { //純下載下傳方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName);
}
byte[] buf = new byte[1024];
int len = 0;
BufferedInputStream br = null;
OutputStream out = null;
try {
br = new BufferedInputStream(new FileInputStream(f));
out = response.getOutputStream();
while ((len = br.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} catch (Exception e) {
//e.printStackTrace();
} finally {
if (br != null) {
br.close();
br = null;
}
if (out != null) {
out.close();
out = null;
}
}
}
本源代碼是基于axman的版本,根據實際需要稍微改了改,我用的是weblogic,當下載下傳.xls等檔案時如果使用者選擇取消則有時報Connection reset by peer:socket write error,其他類型如.doc檔案則不會出錯,tomcat下不知道有沒有這個問題,網上查了半天不知是以然,但有一點可以肯定,就是它并不影響程式的正常運作,是以我把錯誤輸出語句注釋掉了。