How to set the path to “context path” for uploaded files using Apache Common fileupload?

谁都会走 提交于 2019-12-05 12:27:28
BalusC

The java.io.File acts on the local disk file system and knows absolutely nothing about the context it is running in. You should not expect it to find the "right" location when you pass a relative web path in. It would become relative to the current working directory which is dependent on how you started the environment. You don't want to be dependent on that.

You can use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system path.

String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...

That said, I hope that you're aware that the deploy folder isn't the right location for uploaded files which are supposed to be saved permanently. Everything will get lost when you redeploy the webapp. See also How to write a file to resource/images folder of the app?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!