Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload() 

Source Link

Document

Constructs an uninitialised instance of this class.

Usage

From source file:com.qualogy.qafe.web.UploadService.java

public String uploadFile(HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload();
    String errorMessage = "";
    byte[] filecontent = null;
    String appUUID = null;//from w w w  .  j  a  v a2s .  co  m
    String windowId = null;
    String filename = null;
    String mimeType = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    try {
        FileItemIterator fileItemIterator = upload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream item = fileItemIterator.next();
            inputStream = item.openStream();
            // Read the file into a byte array.
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len = 0;
            while (-1 != (len = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, len);
            }
            if (filecontent == null) {
                filecontent = outputStream.toByteArray();
                filename = item.getName();
                mimeType = item.getContentType();
            }

            if (item.getFieldName().indexOf(APP_UUID) > -1) {
                appUUID = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1);
            }
            if (item.getFieldName().indexOf(APP_WINDOWID) > -1) {
                windowId = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1);
            }
        }

        if ((appUUID != null) && (windowId != null)) {
            if (filecontent != null) {
                int maxFileSize = 0;
                if (ApplicationCluster.getInstance()
                        .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) {
                    String maxUploadFileSzie = ApplicationCluster.getInstance()
                            .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE);
                    if (StringUtils.isNumeric(maxUploadFileSzie)) {
                        maxFileSize = Integer.parseInt(maxUploadFileSzie);
                    }
                }

                if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) {
                    Map<String, Object> fileData = new HashMap<String, Object>();
                    fileData.put(FILE_MIME_TYPE, mimeType);
                    fileData.put(FILE_NAME, filename);
                    fileData.put(FILE_CONTENT, filecontent);

                    String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString();
                    appUUID = concat(appUUID, windowId);

                    ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData);

                    return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID;
                } else {
                    errorMessage = "The maxmimum filesize in bytes is " + maxFileSize;
                }
            }
        } else {
            errorMessage = "Application UUID not specified";
        }
        inputStream.close();
        outputStream.close();
    } catch (Exception e) {
        errorMessage = e.getMessage();
    }

    return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage;
}

From source file:com.sifiso.dvs.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;//from  w ww .  jav  a2 s  .c om
    File rootDir;
    try {
        rootDir = dvsProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File doctorFileDir = null, surgeryDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getSurgeryID());
                            if (dto.getDoctorID() > 0) {
                                doctorFileDir = createDoctorDirectory(surgeryDir, doctorFileDir,
                                        dto.getDoctorID());
                            }

                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getPatientfileID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getPatientfileID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getPatientfileID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.FILES_DOCTOR:
                    imageFile = new File(doctorFileDir, fileName);
                    break;
                case PhotoUploadDTO.FILES_SURGERY:
                    imageFile = new File(surgeryDir, fileName);
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

From source file:fedora.server.management.UploadServlet.java

/**
 * The servlet entry point. http://host:port/fedora/management/upload
 *//*ww w .  ja  v a 2s. co  m*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, request);
    try {
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, looking for "file"
        InputStream in = null;
        FileItemIterator iter = upload.getItemIterator(request);
        while (in == null && iter.hasNext()) {
            FileItemStream item = iter.next();
            LOG.info("Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName());
            if (!item.isFormField() && item.getFieldName().equals("file")) {
                in = item.openStream();
            }
        }
        if (in == null) {
            sendResponse(HttpServletResponse.SC_BAD_REQUEST, "No data sent.", response);
        } else {
            sendResponse(HttpServletResponse.SC_CREATED, s_management.putTempStream(context, in), response);
        }
    } catch (AuthzException ae) {
        throw RootException.getServletException(ae, request, "Upload", new String[0]);
    } catch (Exception e) {
        e.printStackTrace();
        sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + ": " + e.getMessage(), response);
    }
}

From source file:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();

    // Parse the request
    try {//from www. j  a v  a2 s  .  c  o m
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }
            } else {
                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.add(name, file);
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:com.googlecode.npackdweb.RepUploadAction.java

@Override
public Page perform(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    List<String> messages = new ArrayList<String>();

    Found f = null;/*from ww w .j ava  2 s  . c o m*/
    String tag = "unknown";
    boolean overwrite = false;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream stream = item.openStream();

                try {
                    if (item.isFormField()) {
                        if (item.getFieldName().equals("tag")) {
                            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
                            tag = r.readLine();
                        } else if (item.getFieldName().equals("overwrite")) {
                            overwrite = true;
                        }
                    } else {
                        f = process(stream);
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (FileUploadException e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    } else {
        tag = req.getParameter("tag");
        String rep = req.getParameter("repository");
        overwrite = req.getParameter("overwrite") != null;
        f = process(new ByteArrayInputStream(rep.getBytes("UTF-8")));
    }

    if (f != null) {
        boolean isAdmin = NWUtils.isAdminLoggedIn();

        for (PackageVersion pv : f.pvs) {
            pv.tags.add(tag);
        }

        Objectify ofy = DefaultServlet.getObjectify();
        List<Key<?>> keys = new ArrayList<Key<?>>();
        for (License lic : f.lics) {
            keys.add(lic.createKey());
        }
        for (PackageVersion pv : f.pvs) {
            keys.add(pv.createKey());
        }
        for (Package p : f.ps) {
            keys.add(p.createKey());
        }

        Map<Key<Object>, Object> existing = ofy.get(keys);

        Stats stats = new Stats();
        Iterator<PackageVersion> it = f.pvs.iterator();
        while (it.hasNext()) {
            PackageVersion pv = it.next();
            PackageVersion found = (PackageVersion) existing.get(pv.createKey());
            if (found != null) {
                stats.pvExisting++;
                if (!overwrite)
                    it.remove();
            }
        }

        Iterator<License> itLic = f.lics.iterator();
        while (itLic.hasNext()) {
            License pv = itLic.next();
            License found = (License) existing.get(pv.createKey());
            if (found != null) {
                stats.licExisting++;
                if (!overwrite)
                    itLic.remove();
            }
        }

        Iterator<Package> itP = f.ps.iterator();
        while (itP.hasNext()) {
            Package p = itP.next();
            Package found = (Package) existing.get(p.createKey());
            if (found != null) {
                stats.pExisting++;
                if (!overwrite)
                    itP.remove();
            }
        }

        for (PackageVersion pv : f.pvs) {
            Package p = ofy.find(new Key<Package>(Package.class, pv.package_));
            if (p != null && !p.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + pv.package_);
        }

        for (Package p : f.ps) {
            Package p_ = ofy.find(new Key<Package>(Package.class, p.name));
            if (p_ != null && !p_.isCurrentUserPermittedToModify())
                messages.add("You do not have permission to modify this package: " + p.name);
        }

        if (f.lics.size() > 0) {
            if (isAdmin)
                ofy.put(f.lics);
            else
                messages.add("Only an administrator can change licenses");
        }

        ofy.put(f.pvs);

        for (Package p : f.ps) {
            NWUtils.savePackage(ofy, p, true);
        }

        if (overwrite) {
            stats.pOverwritten = stats.pExisting;
            stats.pvOverwritten = stats.pvExisting;
            stats.licOverwritten = stats.licExisting;
            stats.pAppended = f.ps.size() - stats.pOverwritten;
            stats.pvAppended = f.pvs.size() - stats.pvOverwritten;
            stats.licAppended = f.lics.size() - stats.licOverwritten;
        } else {
            stats.pAppended = f.ps.size();
            stats.pvAppended = f.pvs.size();
            stats.licAppended = f.lics.size();
        }
        messages.add(stats.pOverwritten + " packages overwritten, " + stats.pvOverwritten
                + " package versions overwritten, " + stats.licOverwritten + " licenses overwritten, "
                + stats.pAppended + " packages appended, " + stats.pvAppended + " package versions appended, "
                + stats.licAppended + " licenses appended");
    } else {
        messages.add("No data found");
    }

    return new MessagePage(messages);
}

From source file:com.artgameweekend.projects.art.web.TagUploadServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from   w w w  .  j a va2s . c o m

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(500000);
        res.setContentType(Constants.CONTENT_TYPE_TEXT);
        PrintWriter out = res.getWriter();
        byte[] image = null;

        Tag tag = new Tag();
        TagImage tagImage = new TagImage();
        TagThumbnail tagThumbnail = new TagThumbnail();
        String contentType = null;
        boolean bLandscape = false;

        try {
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                    out.println("Got a form field: " + item.getFieldName());
                    if (Constants.PARAMATER_NAME.equals(item.getFieldName())) {
                        tag.setName(IOUtils.toString(in));
                    }
                    if (Constants.PARAMATER_LAT.equals(item.getFieldName())) {
                        tag.setLat(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LON.equals(item.getFieldName())) {
                        tag.setLon(Double.parseDouble(IOUtils.toString(in)));
                    }
                    if (Constants.PARAMATER_LANDSCAPE.equals(item.getFieldName())) {
                        bLandscape = IOUtils.toString(in).equals("on");
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    contentType = item.getContentType();

                    out.println("--------------");
                    out.println("fileName = " + fileName);
                    out.println("field name = " + fieldName);
                    out.println("contentType = " + contentType);

                    try {
                        image = IOUtils.toByteArray(in);
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
        } catch (SizeLimitExceededException e) {
            out.println("You exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
        }

        contentType = (contentType != null) ? contentType : "image/jpeg";

        if (bLandscape) {
            image = rotate(image);
        }
        tagImage.setImage(image);
        tagImage.setContentType(contentType);
        tagThumbnail.setImage(createThumbnail(image));
        tagThumbnail.setContentType(contentType);

        TagImageDAO daoImage = new TagImageDAO();
        daoImage.create(tagImage);

        TagThumbnailDAO daoThumbnail = new TagThumbnailDAO();
        daoThumbnail.create(tagThumbnail);

        TagDAO dao = new TagDAO();
        tag.setKeyImage(tagImage.getKey());
        tag.setKeyThumbnail(tagThumbnail.getKey());
        tag.setDate(new Date().getTime());
        dao.create(tag);

    } catch (Exception ex) {

        throw new ServletException(ex);
    }
}

From source file:com.runwaysdk.web.SecureFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }//w  w  w  .java  2s. c o  m

    String fileId = req.getParameter("sessionId").toString().trim();
    FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId);
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request

        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                String fileName = fullName.substring(0, extensionInd);
                String extension = fullName.substring(extensionInd + 1);
                InputStream stream = item.openStream();

                BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream);

                // return the vault id to the dhtmlxVault callback
                req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId());
            }
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    } catch (RuntimeException e) {
        req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage());
    }
}

From source file:com.intuit.tank.util.UserNameFilterTest.java

/**
 * Run the void doFilter(ServletRequest,ServletResponse,FilterChain) method test.
 *
 * @throws Exception/*from   ww w .j  a  v a2 s  .com*/
 *
 * @generatedBy CodePro at 12/15/14 3:53 PM
 */
@Test(expected = java.io.IOException.class)
public void testDoFilter_1() throws Exception {
    UserNameFilter fixture = new UserNameFilter();
    ServletRequest request = new JerseyAdaptedHttpServletRequest(
            new MultipartRequest(new DummyRequest(), new ServletFileUpload()), new MediaType());
    ServletResponse response = new JerseyAdaptedHttpServletResponse(new DummyResponse(), (WebApplication) null);
    FilterChain chain = null;

    fixture.doFilter(request, response, chain);

}

From source file:com.sifiso.yazisa.util.PhotoUtil.java

public ResponseDTO downloadPhotos(HttpServletRequest request, PlatformUtil platformUtil)
        throws FileUploadException {
    logger.log(Level.INFO, "######### starting PHOTO DOWNLOAD process\n\n");
    ResponseDTO resp = new ResponseDTO();
    InputStream stream = null;/*from  w w w  . ja va  2 s  .c  om*/
    File rootDir;
    try {
        rootDir = YazisaProperties.getImageDir();
        logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath());
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Properties file problem", ex);
        resp.setMessage("Server file unavailable. Please try later");
        resp.setStatusCode(114);

        return resp;
    }

    PhotoUploadDTO dto = null;
    Gson gson = new Gson();
    File schoolDir = null, classDir = null, parentDir = null, teacherDir = null, studentDir = null;
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            stream = item.openStream();
            if (item.isFormField()) {
                if (name.equalsIgnoreCase("JSON")) {
                    String json = Streams.asString(stream);
                    if (json != null) {
                        logger.log(Level.INFO, "picture with associated json: {0}", json);
                        dto = gson.fromJson(json, PhotoUploadDTO.class);
                        if (dto != null) {
                            if (dto.getSchoolID() > 0) {
                                schoolDir = createSchoolDirectory(rootDir, schoolDir, dto.getSchoolID());
                            }

                            if (dto.getClassID() > 0) {
                                classDir = createClassDirectory(schoolDir, classDir, dto.getClassID());
                            }
                            if (dto.getParentID() > 0) {
                                parentDir = createParentDirectory(schoolDir, parentDir);
                            }
                            if (dto.getTeacherID() > 0) {
                                teacherDir = createTeacherDirectory(schoolDir, teacherDir);
                            }
                            if (dto.getStudentID() > 0) {
                                studentDir = createStudentDirectory(rootDir, studentDir);
                            }
                        }
                    } else {
                        logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL..");
                    }
                }
            } else {
                File imageFile = null;
                if (dto == null) {
                    continue;
                }
                DateTime dt = new DateTime();
                String fileName = "";
                if (dto.isIsFullPicture()) {
                    fileName = "f" + dt.getMillis() + ".jpg";
                } else {
                    fileName = "t" + dt.getMillis() + ".jpg";
                }
                if (dto.getSchoolID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getSchoolID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getSchoolID() + ".jpg";
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getTeacherID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getTeacherID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getTeacherID() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getClassID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        } else {
                            fileName = "t" + dto.getClassID() + "-" + new Date().getYear() + ".jpg";
                        }
                    }
                }
                if (dto.getSchoolID() != null) {
                    if (dto.getParentID() != null) {
                        if (dto.isIsFullPicture()) {
                            fileName = "f" + dto.getParentID() + ".jpg";
                        } else {
                            fileName = "t" + dto.getParentID() + ".jpg";
                        }
                    }
                }

                if (dto.getStudentID() != null) {
                    if (dto.isIsFullPicture()) {
                        fileName = "f" + dto.getStudentID() + ".jpg";
                    } else {
                        fileName = "t" + dto.getStudentID() + ".jpg";
                    }
                }

                //
                switch (dto.getPictureType()) {
                case PhotoUploadDTO.SCHOOL_IMAGE:
                    imageFile = new File(schoolDir, fileName);
                    break;
                case PhotoUploadDTO.CLASS_IMAGE:
                    imageFile = new File(classDir, fileName);
                    break;
                case PhotoUploadDTO.PARENT_IMAGE:
                    imageFile = new File(parentDir, fileName);
                    break;
                case PhotoUploadDTO.STUDENT_IMAGE:
                    imageFile = new File(studentDir, fileName);
                    break;
                }

                writeFile(stream, imageFile);
                resp.setStatusCode(0);
                resp.setMessage("Photo downloaded from mobile app ");
                //add database
                System.out.println("filepath: " + imageFile.getAbsolutePath());
                //create uri
                /*int index = imageFile.getAbsolutePath().indexOf("monitor_images");
                 if (index > -1) {
                 String uri = imageFile.getAbsolutePath().substring(index);
                 System.out.println("uri: " + uri);
                 dto.setUri(uri);
                 }
                 dto.setDateUploaded(new Date());
                 if (dto.isIsFullPicture()) {
                 dto.setThumbFlag(null);
                 } else {
                 dto.setThumbFlag(1);
                 }
                 dataUtil.addPhotoUpload(dto);*/

            }
        }

    } catch (FileUploadException | IOException | JsonSyntaxException ex) {
        logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex);
        throw new FileUploadException();
    }

    return resp;
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();

        try {/* www  .j  a va 2s .com*/
            // Parse the request
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    System.out.println(
                            "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                } else {
                    System.out
                            .println("File field " + name + " with file name " + item.getName() + " detected.");
                    DataSource source = createDataSource(item);
                    SessionManager.get().getCurrentComposeMessage().addComposeAttachment(source);
                }

                JSONObject jsonResponse = null;
                try {
                    jsonResponse = new JSONObject();
                    jsonResponse.put("success", true);
                    jsonResponse.put("error", "Upload successful");
                } catch (Exception e) {

                }

                Writer w = new OutputStreamWriter(response.getOutputStream());
                w.write(jsonResponse.toString());
                w.close();

                stream.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}