开发者

Why can't upload three files with FileUpload?

开发者 https://www.devze.com 2023-02-15 05:26 出处:网络
i\'m trying to upload three images to my server, is working, but upload always the last file selected by the user, not the three selected.

i'm trying to upload three images to my server, is working, but upload always the last file selected by the user, not the three selected.

Here's my code:

protected void doPost(HttpServletRequest request, HttpServletResponse response){
    boolean multipart = ServletFileUpload.isMultipartConte开发者_开发技巧nt(request);

    if (multipart) {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            List items = uploadHandler.parseRequest(request);

            Iterator itr = items.iterator();

            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                File file = new File(dir, generateNewName());
                item.write(file);
            }
        } catch (FileUploadException ex) {
        } catch (Exception ex) {
        }
    }
}

-- UPDATE:

<html>
    <head>
        <title>Upload</title>
    </head>
    <body>
        <form action="Upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file1" />
            <br />

            <input type="file" name="file2" />
            <br />

            <input type="file" name="file3" />
            <br />

            <input type="submit" value="Enviar" />

        </form>
    </body>

UPDATE 2:

I found my error: when i called the method generateNewName() return a string that contains (date)+(hour)+(miliseconds) , i think this should be enough to generate a new name every time but returns the same name always, so this way rewrite the same file every time.

Sorry for any inconvenience and thank you guys by the help.

Best regards, Valter Henrique.


Even though you nailed down your own problem (kudos for you, I'd suggest to post an answer on this question yourself), I would still like to recommend to use File#createTempFile() instead to generate an unique filename. This Java SE provided API is guaranteed to create an unique file on the given path.

Here's an example which does that based on the name/extension of the uploaded file.

String fileName = FilenameUtils.getName(item.getName());
String fileNamePrefix = FilenameUtils.getBaseName(fileName) + "_";
String fileNameSuffix = "." + FilenameUtils.getExtension(fileName);

File file = File.createTempFile(fileNamePrefix, fileNameSuffix, dir);
item.write(file);
// ...

The FilenameUtils is from Commons IO which you should already have in the classpath anyway since it's a required dependency of Commons FileUpload.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号