当用户选择文件时,它将存储在用户在上传过程中输入的不同名称的文件夹(已在ProjectConfig文件中设置的路径)中。 这是我的Servlet中的代码,
new ProjectConfig(); // For setting path for storing image
String dealerGalleryPath = ProjectConfig.get("dealergallery");
DiskFileItemFactory factory = new DiskFileItemFactory();
int locationid=2;
ServletFileUpload upload = new ServletFileUpload(factory);
String fileName = "";
try
{
java.io.File fnew = null;
//System.out.println(getServletContext().getRealPath("/images"));
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
//System.out.println("Field Name is.."+fieldName);
fileName = fi.getName();
if(fi.getName() != null && fi.getName().trim().length() != 0)
{
//System.out.println("File Name is.."+fileName);
String realWebPath = dealerGalleryPath+locationid+"/"+fi.getName();
fnew = new java.io.File(realWebPath); // **What to do here to change name of file??**
fi.write(fnew);
System.out.println("Success");
//commonutil.setProductimage(fi.getName());
}
}
}
System.out.println("fileName::"+fileName);
request.setAttribute("ImageName", fileName);
RequestDispatcher rd = request.getRequestDispatcher("/jsp/ImageTesting.jsp");
rd.forward(request, response);
}catch(Exception e)
{
e.printStackTrace();
}
我对本网站的问题进行了审核..但是没有找到相关的答案。提前谢谢
答案 0 :(得分:0)
下一代码在我的网站上运行良好:
filePath = "upload/"; // DIRECTORY IN THE ROOT OF YOUR WEBSITE.
fileName = fi.getName(); // ORIGINAL FILENAME (YOU DONT WANT IT).
file = new File( filePath + "newname" ); // NEW FILE WITH NEW NAME.
try { fi.write( file ); } // WRITES ORIGINAL FILE INTO NEW FILE.
catch ( Exception ew ) { /* HANDLE ERROR HERE */ }
您的问题是:// 如何更改文件名? 好吧,你不会在那里改变任何东西,但是代码中的两行只是改变了" fi.getName()"为你想要的新名字。