<分区>
我正在用 jsp 做一个简单的文件上传。我似乎已经被这个简单的路径问题阻止了。我在 Windows 上开发,但可能会部署在 Linux 机器上。所以我在 mywebsite/tempfiledir 和 mywebsite/finalfiledir 下有 tmpdir 和 finaldir
所以我使用这段代码(servlet 的片段)
public class SyncManagerServlet extends HttpServlet {
private static final String TMP_DIR_PATH = "/tempfiledir";
private File tempDir;
private static final String DESTINATION = "/finalfiledir";
private File destinationDir;
public void init(ServletConfig config){
try {
super.init(config);
tempDir = new File(getAbsolute(TMP_DIR_PATH));
if(!tempDir.isDirectory()){
throw new ServletException(TMP_DIR_PATH + " is not a Directory");
}
destinationDir = new File(getAbsolute(DESTINATION));
if(!destinationDir.isDirectory()){
throw new ServletException(DESTINATION + " is not a Directory");
}
} catch (ServletException ex) {
Logger.getLogger(OrliteSyncManagerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String email = request.getParameter("email");
String path = request.getContextPath();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setRepository(tempDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()){
FileItem item = (FileItem) itr.next();
if( item.isFormField() && item != null ){
out.println("<html>");
out.println("<head>");
out.println("<body>");
out.println("your email: " + item.getString() + " has been submited and context path is "+ request.getContextPath() );
out.println("</body>");
out.println("</head>");
out.println("</html>");
} else {
out.println("the uploaded file name is : " + item.getName());
out.println("content type is : " + item.getContentType());
out.println("Size is : " + item.getSize());
File file = new File(destinationDir, FilenameUtils.getName(item.getName()));
item.write(file);
}
public String getAbsolute(String relativepath){
return getServletContext().getRealPath(relativepath);
}
//......
}
我有这个异常(exception)
java.io.FileNotFoundException: D:\WORK\java\netbeansProject\Projects\mywebsite-webapp\target\mywebsite\finalfiledir (Access is denied)
我不明白为什么相对路径失败了。 我注意到在很多在线示例中,人们使用 tempdir 的完整路径。 所以在我不得不担心 linux 部署的情况下,解决方法是什么?但首先我想了解为什么我给出的路径是错误的。
感谢阅读本文! 所以这里有 2 个问题
1 如何解决这个路径即时问题?
2 如何以更便携的方式做到这一点(考虑到 linux 特权)?
谢谢!