You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@turbine.apache.org by Jeffery Painter <je...@jivecast.com> on 2018/10/04 16:46:04 UTC

turbine 5.0 file upload processing

Recording this for archival purposes...

In turbine-4.0.1 and prior, file uploads were processed through the
data.getParameters().getFileItem("file_field_name") method and returned
a FileItem object.

With Turbine-5.0 and later, you will need to migrate this code using the
new Part object from the servlet spec.  This actually saves you some
time since you don't have to convert the FileItem to a byte array and
then into an InputStream for processing.. you auto-magically get an
getInputStream() method on your javax.servlet.http.Part object to then
do as you please...


Upload files are handled this way now...if say you want to read an
uploaded text file line by line:

        // all file items are now parts
        Part fileItem = data.getParameters().getPart("file");

        if (fileItem != null) {

            InputStream is = fileItem.getInputStream();
            BufferedReader bfReader = null;
            try {
                bfReader = new BufferedReader(new InputStreamReader(is));
                String line = null;
                while ((line = bfReader.readLine()) != null) {

                    // do something with the input here ...

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (Exception ex) {

                }
            }
        }


And if you really do need a byte array (for example to store the
contents as a binary object in the database), you can do this using the
following method calls.

  InputStream is = fileItem.getInputStream();
  byte[] byteArray = IOUtils.toByteArray(is);


-- 
Jeff Painter