Search code examples
javajspservletsapache-commons-fileupload

Apache FileItem to byte array?


I'm using,

org.​apache.​commons.​fileupload.​FileItem

I want to upload a file using JSP Servlet using,

<form action="someAction" method="post"  enctype="multipart/form-data">

Is there a way to convert this file/item to a byte array? Currently, I have done in my servlet,

        List<FileItem> multiparts = upload.parseRequest(req);
        for (FileItem item : multiparts) {
            if (!item.isFormField()) {
                //Custom class need byte array as the file's content
                CustomClass doc = new CustomClass();
                //Need to set byte array value to this
                doc.setValue(byte array);
                item --> byte array????
            }
        }

Solution

  • From the javadoc (emphasis is mine):

    After retrieving an instance of this class from a FileUpload instance (see #parseRequest(javax.servlet.http.HttpServletRequest)), you may either request all contents of the file at once using get() or request an InputStream with getInputStream() and process the file without attempting to load it into memory, which may come handy with large files.