Search code examples
javajspservletsfile-rename

How can i chage name of image using java while uploading and save in folder?


<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>

this is my index.jsp page. This Servlet is DemoServlet when user click on submit button it will go here.while in jsp page suppose Image_Name given by user is IPL and actual name of image is funny.jpg then while saving the image it should store as IPL.png,here i'm able to upload image correctly with funny.jpg,but i need to save image as given name in text field of index.jsp page

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();
        }
    }
}   

}

and this is java class

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;
}

}

Could anybody guide me how to change this dynamically.Thanks in advance.


Solution

  • I don't know how Servlet's and the like work however i can give you a rundown of what you need to do.

    In DemoServlet you need to take in the input of the Image_Name field and make that one of your parameters of FileUpload

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

    Because currently your processFile method is taking the name of the file from your FileItemStream. You need to change it from that to your actual fileName

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

    to

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