java 从 FileItem 的名称中仅提取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7411964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:51:20  来源:igfitidea点击:

Extract only file name From FileItem's name

javaservletsapache-commons

提问by Dinushan

In apache commons file uploading the uploaded files are available as FileItem objects.
If I get the name of such file item by using fileitem.getName()it returns the full path (ex: C:\Test\test.txt).

Is there any way to get only the file name.
What I actually need is to save the uploaded file as temp file using File.createTempFile()
but the name and extension of the temp file should be the same as the uploaded file rather than a random name(like temp.tmp)

在 apache commons 文件上传中,上传的文件可用作 FileItem 对象。
如果我通过使用fileitem.getName()它获取此类文件项的名称,则返回完整路径(例如:)C:\Test\test.txt

有没有办法只获取文件名。
我真正需要的是将上传的文件保存为临时文件,File.createTempFile()
但临时文件的名称和扩展名应与上传的文件相同,而不是随机名称(如temp.tmp

回答by JoseK

Try what the docs say

试试文档说的

Why does FileItem.getName() return the whole path, and not just the file name?

Internet Explorer provides the entire path to the uploaded file and not just the base file name. Since FileUpload provides exactly what was supplied by the client (browser), you may want to remove this path information in your application. You can do that using the following method from Commons IO (which you already have, since it is used by FileUpload).

为什么 FileItem.getName() 返回整个路径,而不仅仅是文件名?

Internet Explorer 提供了上传文件的完整路径,而不仅仅是基本文件名。由于 FileUpload 提供的正是客户端(浏览器)提供的内容,因此您可能希望在应用程序中删除此路径信息。您可以使用 Commons IO 中的以下方法(您已经拥有,因为它被 FileUpload 使用)来做到这一点。

String fileName = item.getName();
 if (fileName != null) {
     fileName = FilenameUtils.getName(fileName);
 }