Hi,
I want to get only the filename from the entire path in a file dialog in JSP. Right now I am using type "file" in input tag.
any help will be appreciated.
cheers!
Hi,
I want to get only the filename from the entire path in a file dialog in JSP. Right now I am using type "file" in input tag.
any help will be appreciated.
cheers!
Modern browsers intentionally prevent access to the full client file path for privacy/security; most code should rely on the filename only (some browsers return a fake path like C:\fakepath\). already pointed out both client- and server-side options — here are up-to-date, practical ways to get just the filename and caveats to keep in mind.
The most reliable client-side approach is the HTML5 File API (useful when the filename is needed before upload):
<input type="file" id="fileInput">
<script>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', () => {
const f = fileInput.files && fileInput.files[0];
if (f) {
console.log(f.name); // filename only
} else {
// fallback for very old browsers
const nameFallback = fileInput.value.replace(/^.*[\\\/]/, '');
console.log(nameFallback);
}
});
</script> Server-side (when the upload reaches the server) is the authoritative place to decide what to store. With Servlet 3+ use Part.getSubmittedFileName() and strip any path elements safely:
Part p = request.getPart("fileField");
String raw = p.getSubmittedFileName();
String filename = java.nio.file.Paths.get(raw).getFileName().toString(); For older stacks using Commons FileUpload, FileItem.getName() may return a client path on some UAs; pass that value through org.apache.commons.io.FilenameUtils.getName(...) to get the base name.
Important cautions: never trust client-supplied filenames for storage — sanitize/remove dangerous characters, limit length, enforce type/size checks, and use server-generated unique names or directories to avoid collisions and path traversal. For reference on the File API and input:file behavior see the MDN docs: input type="file" and File.name.
There is not jsp dialog user interface for file selection. It's a input type file html tag.
If you want to get filename only in your server side (java) code then use,
File s=new File("c:\\aa\\b.txt");
System.out.println(s.getName()); Use following javascript code to get filename.
....
<script type="text/javascript">
function doit() {
var v=form1.file.value;
alert(v.substring(v.lastIndexOf("\\")+1));
}
</script>
....
<form method="post" name="form1">
<input type="file" name="file"/>
<input type="button" value="Test" onclick="doit()"/>
</form> We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.