javaservletsfile-uploadapache-commons-fileupload

File is Attached or not in File field?


I have the following code:

if (formItems != null && formItems.size() > 0) {
    // iterates over form's fields
    for (FileItem item : formItems) {
        // processes only fields that are not form fields
        if (!item.isFormField()) {
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;
            File storeFile = new File(filePath);

            // saves the file on disk
            item.write(storeFile);
            session.setAttribute("image", fileName);
        }
        // processes only form fields
        else {
            String fieldname = item.getFieldName();
            String fieldvalue = item.getString();
            session.setAttribute(fieldname, fieldvalue);
        }
    }
}

I want to check a file is attached or not first. If attached then only upload the file. I have tried this:

if(item==null)

But this won't work. How can I check if a file attached or not? I have a file field:

<input type="file" name="image"/>

Solution

  • The item is never null.

    Just check if the FileItem#getName() (the file name) is empty and/or FileItem#getSize() (the file size) equals to 0.

    In your particular case, with an <input type="file" name="image"/>, that'll be :

    if (!item.isFormField()) {
        if ("image".equals(item.getFieldName())) {
            if (item.getName() == null || item.getName().isEmpty()) {
                // No file was been selected.
            }
    
            if (item.getSize() == 0) {
                // No file was been selected, or it was an empty file.
            }
        }
    }