Question

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"/>
Was it helpful?

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

OTHER TIPS

You can use the following code to check whether your fileupload control has any value. filename is the name of my fileupload control

if ("filename".equals(item.getFieldName()) && item.getSize() > 0) {
    // your code here
} else {
    // Exception handling as no file chosen/attached
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top