0

当用户选择文件时,它将以用户在上传过程中输入的不同名称存储在文件夹中(路径已在 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();
    }

我在这个网站上浏览了问题..但找不到相关的答案。先感谢您

4

1 回答 1

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()”更改为您想要的新名称。

于 2014-05-16T20:25:32.020 回答