今日遇到一個問題:做了一個文件下載的功能,本機裝的是Tomcat,測試的時候能運行過,但是發佈到weblogic上面的時候就一直報錯:未找到文件。
百度過後發現:
/**
* 文件下載
* 文件放在webapp/lssi/fileresoure 下面,
* 如:publicBusniess下面的徵地農轉非登記表,則在fileresoure 下面新建publicbusniess文件夾,並且將徵地農轉非登記表.xls 放在該目錄
* 在具體Action裏面調用時格式爲:download("publicBusiness/徵地農轉非登記表.xls");
* @param filePath 文件路徑及文件名
* @return
* @author chencj
* @throws Exception
*/
public String downloadFile(String filePath) throws Exception{
//不能使用ServletActionContext.getServletContext().getRealPath("/")獲取文件路徑
//程序打包發佈到weblog上之後,getRealPath返回的是null。該項目不存在所謂的文件系統中的目錄,在tomcat下面發佈打包應用的時候,它會把包解壓,所以即使都是打包
//項目發佈上去tomcat上面還是可以支持getRealPath().
//String fullFilePath1 =ServletActionContext.getServletContext().getRealPath("/")+"lssi/fileresource/"+filePath;
//String fullFilePath1 = request.getSession().getServletContext().getResource("lssi/fileresource/"+filePath).getFile();
//String path=this.getClass().getClassLoader().getResource("/").getPath();
String fullFilePath = this.getClass().getClassLoader().getResource("/").getPath();
//this.getClass().getClassLoader().getResource("/").getPath()取出來的路徑中空格會轉換爲%20這種在文件目錄中是不能被識別的,所以需要重新編碼爲utf-8
fullFilePath = URLDecoder.decode(fullFilePath,"utf-8");
//this.getClass().getClassLoader().getResource("/").getPath()獲取出來的路徑是到WEB-INF/classes下面的路徑,但是weblog可能會存在對此目錄訪問權限控制,所以文件最好不要放在該目錄下面。自己處理獲取需要的目錄
fullFilePath = fullFilePath.replace("WEB-INF/classes/", "")+"lssi/fileresource/"+filePath;
/*讀取文件*/
File file = new File(fullFilePath);
/*如果文件存在*/
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), "utf-8");
response.reset();
//設置下載文件的類型
response.setContentType("application/x-msdownload");
//添加文件名字
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
//添加文件的大小信息
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/*如果文件長度大於0*/
if (fileLength != 0) {
/*創建輸入流*/
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
//獲得輸出網絡流
ServletOutputStream servletOS = response.getOutputStream();
int readLength =0;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}else{
throw new AppException(fullFilePath+" 未找到!");
}
return null;
}
如果僅僅提供下載的情況 也可以選擇使用 getResourceAsStream()返回的是一個InputStream