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

StackOverflow https://stackoverflow.com/questions/23074240

Вопрос

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

Это было полезно?

Решение

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");

Другие советы

You can change the name of image in your java class code.

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;

}

you will have to pass the file name in the method.
instead of item.getName() you can give your name.

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

            }

In the code above you can change the file name at any time and it will automatically save with this name.

//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");
        }

    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top