如何在上传和保存在文件夹中时使用java更改图像名称?

时间:2014-04-15 03:38:26

标签: java jsp servlets file-rename

<body>
    <form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
        <input type="file"  name="file" />
        Image_Name:<input type="text" name="file"/>
        <input type="submit" value="Go"/>
    </form>
</body>

这是我的index.jsp页面。 这个Servlet是DemoServlet,当用户点击提交按钮时它将会到这里。而在jsp页面中假设用户给出的Image_Name是IPL,图像的实际名称是funny.jpg然后在保存图像时它应该存储为IPL.png,这里我和#39;能够使用funny.jpg正确上传图像,但我需要在index.jsp页面的文本字段中将图像保存为给定名称

public class DemoServlet extends HttpServlet {   

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Date date = new Date();
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fieldname = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fieldname + ":" + value + "</br>");
                } else {
                    String TempPath = getServletContext().getRealPath("");
                    String path = TempPath.substring(0, TempPath.indexOf("build"));
                    if (FileUpload.processFile(path, item)) {
                        out.println("File Uploaded on:" + date + "<br>");
                        response.getWriter().println("Image Upload Successfully");
                    } else {
                        response.getWriter().println("Failed.....Try again");
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
        }
    }
}   

}

这是java类

public class FileUpload {

public static boolean processFile(String path, FileItemStream item) {
    try {
        File f = new File(path + File.separator + "web/images");
        if (!f.exists()) {
            f.mkdir();
        }
        File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
        FileOutputStream fos = new FileOutputStream(savedFile);
        InputStream is = item.openStream();
        int x = 0;
        byte[] b = new byte[1024];
        while ((x = is.read(b)) != -1) {
            fos.write(b, 0, x);
        }
        fos.flush();
        fos.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

}

有人可以指导我如何动态地改变它。提前谢谢。

4 个答案:

答案 0 :(得分:1)

我不知道Servlet等是如何工作的,但我可以给你一个你需要做的事情的概述。

在DemoServlet中,您需要接受Image_Name字段的输入并将其作为FileUpload的参数之一

public static boolean processFile(String path, FileItemStream item, String fileName){
    //Method Code
}

因为目前您的processFile方法正在从FileItemStream中获取文件的名称。您需要将其从实际的fileName更改为

File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());

File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");

答案 1 :(得分:1)

您可以在java类代码中更改图像的名称。

public class FileUpload {

public static boolean processFile(String path, FileItemStream item , String name) {
  try {
    File f = new File(path + File.separator + "web/images");
    if (!f.exists()) {
        f.mkdir();
    }
    File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName()); // instead of item.getName() you can give your name.
    FileOutputStream fos = new FileOutputStream(savedFile);
    InputStream is = item.openStream();
    int x = 0;
    byte[] b = new byte[1024];
    while ((x = is.read(b)) != -1) {
        fos.write(b, 0, x);
    }
    fos.flush();
    fos.close();
    return true;
} catch (Exception e) {
    e.printStackTrace();
}
return false;

}

您必须在方法中传递文件名。
 而不是 item.getName(),您可以提供您的名字。

答案 2 :(得分:0)

        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        System.out.println("In >>>>>>>>>>>>>>> :: "+fileItems);
        while(i.hasNext()){                
            FileItem fi = (FileItem) i.next();
            System.out.println("Val <<<<>>>>>>:: "+fi);
            if(fi.isFormField()){
                String fieldName = fi.getFieldName();
                String val = fi.getString();

                System.out.println(fieldName+" :: Val :: "+val);
            }else{
                String fileName = fi.getName();

                String root = getServletContext().getRealPath("/");
                File path = new File(root+"/uploads");
                if (!path.exists()) {
                    boolean status = path.mkdir();
                }
                File uploadFile = new File(path+"/"+fileName);
                fi.write(uploadFile);

            }

在上面的代码中,您可以随时更改文件名,它将自动以此名称保存。

答案 3 :(得分:-2)

//How does not work in this way?Please tell me another way.
import java.io.File;

public class RenameFileExample {
    public static void main(String[] args)
    {

        File oldfile =new File("oldfile.txt");
        File newfile =new File("newfile.txt");

        File file = new File("oldfilename.png");
        file.renameTo(new File("newfilename.png"));
        System.out.println("Rename To:"+file.getName());

        if(oldfile.renameTo(newfile)){
            System.out.println("Rename succesful");
        }else{
            System.out.println("Rename failed");
        }

    }
}