简体   繁体   中英

how to know how many object type=“file” there are in a jsp

i'm created a form to upload images into a blob field of a mysql database.

In a servlet i get the imagine inside a type="file" field in a jsp page.

  Part filePart = request.getPart("Name_of_the_FILE_fields");  

Now i want to allow user to upload more images at the same time, so i put in my jsp page a lot of type="file" field.

I thought that i could do something like this

 Part filePart[] =request.getParameterValues("Name_of_the_FILE_fields");

but of course this is not the right way to do it.

Here's a script that you can use.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    String savePath = request.getServletContext().getRealPath("") + File.separator + "files";       

    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    for (Part part : request.getParts()) {
        String fileName = findFileName(part);
        part.write(savePath + File.separator + fileName);
    }   
}

private String findFileName(Part part) {
    String[] items = part.getHeader("content-disposition").split(";");
    for (String item : items) {
        if (item.trim().startsWith("filename")) {
            return item.substring(item.indexOf("=") + 2, item.length() - 1);
        }
    }
    return "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM