我想获取要上传的文件的名称。 目的是获取文件的完整路径(包括带扩展名的文件名)。 jsp: -
<form action="go" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
的servlet: -
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String filename=request.getParameter("fname"); //unable to get fname
MultipartRequest m=new MultipartRequest(request,"d:/new");
String filePath="d:/new".concat(filename);
out.print("successfully uploaded");
out.print(filePath);
}
答案 0 :(得分:1)
A.Plain Servlet解决方案:
<强> 1。从HttpServletRequest获取javax.servlet.http.Part
String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = getFileName(part);
}
<强> 2。从Part
获取文件名 /**
* Utility method to get file name from HTTP header content-disposition
*/
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
=============================================== ====
B.Spring based Solution:
使用spring,当您上传文件时,request
是org.springframework.web.multipart.MultipartHttpServletRequest的实例
您可以从MultipartHttpServletRequest获取上传的文件名,如下所示。
// cast request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// get filenames as iterator
Iterator<String> iterator = multipartRequest.getFileNames();
while (iterator.hasNext()) {
String uploadedFileName = (String) iterator.next();
}