Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:UploadDownloadFile.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);//from   w  w  w. j  a va2 s  .  c  o m
    String filePath;
    final String clientip = request.getRemoteAddr().replace(":", "_");
    filePath = "/Users/" + currentuser + "/GlassFish_Server/glassfish/domains/domain1/tmpfiles/Uploaded/"
            + clientip + "/";
    System.out.println("filePath = " + filePath);
    // filePath = "/Users/jhovarie/Desktop/webuploaded/";
    File f = new File(filePath);
    if (!f.exists()) {
        f.mkdirs();
    }

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    //factory.setRepository(new File("c:\\temp"));
    factory.setRepository(new File(filePath));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<a href='" + currenthost + "/UploadDownloadFile/index.html'><< BACK <<</a><br/>");
        String fileName = "";
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println("Target Location = " + filePath);
        out.write(
                "<br/><a href=\"UploadDownloadFile?fileName=" + fileName + "\">Download " + fileName + "</a>");
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println("Error in Process " + ex);
    }
}

From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * Process the uploaded file// w  ww . j  av a2  s  .  c o  m
 * 
 * @param item The multipart form file data.
 * 
 * @return The uploaded file as File object.
 * 
 * @throws Exception
 */
private File processUploadedFile(FileItem item) throws Exception {

    File eml = null;

    // Process a file upload
    if (!item.isFormField()) {

        // Get object information
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();

        String tmpdir = System.getProperty("java.io.tmpdir");

        logger.debug("FILE: " + tmpdir + "/" + fileName);

        eml = new File(tmpdir + "/" + fileName);

        item.write(eml);

    }

    return eml;
}

From source file:controlador.SerCiudadano.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w ww  . j ava  2s. c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //Procesando el archivo .sql con los datos del cnr
    //en esta ruta se guarda temporalmente el archivo .sql
    Bitacora b = new Bitacora();
    String ruta = getServletContext().getRealPath("/") + "pages/procesos/";
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(40960);
        File repositoryPath = new File("/temp");
        diskFileItemFactory.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setSizeMax(81920); // bytes
        upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                //este es el archivo que se envia en el campo file
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(ruta, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            String script = ruta + "" + nombre;
                            //consulta para importar registros
                            if (ConsultasDTO.ejecutar(
                                    "copy padronelectoral from '" + script + "' with (delimiter ',')")) {
                                out.print("Registros importados correctamente");
                            } else {
                                out.print("Hubo un error");
                            }

                        } else {
                            out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                        }
                    }
                } else {
                    //ac recogemos los duis de los magistrados
                    if (item.getFieldName().equals("dui1")) {
                        b.setMagistrado1(item.getString());
                    }
                    if (item.getFieldName().equals("dui2")) {
                        b.setMagistrado2(item.getString());
                    }
                    if (item.getFieldName().equals("dui3")) {
                        b.setMagistrado3(item.getString());
                    }

                }
            }
            //registramos en la base de datos los duis de los magistrados
            //que autorizaron la insercion de datos CNR
            b.setAccion("Registro de datos CNR");
            if (BitacoraDTO.agregarBitacora(b)) {
                out.print("<br>Bitacora agregada");
            } else {
                out.print("<br>Hubo un error al agregar la bitacora");
            }

        } catch (FileUploadException e) {
            out.println("Error Upload: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            out.println("Error otros: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java

public ModelAndView uploadCustomerCaseDocs(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    String responseMessage = "";
    String caseid = "";
    Map model = new HashMap();
    try {//from w  w  w  . j a v a 2  s.c o m
        if ((String) request.getSession().getAttribute(Constants.SESSION_CUSTOMER_ID) != null) {
            FileUploadHandler uh = new FileUploadHandler();
            HashMap hm = uh.getItems(request);
            String companyid = sessionHandlerImpl.getCompanyid(request);
            String customerId = (String) request.getSession().getAttribute("customerid");
            String contactId = (String) request.getSession().getAttribute("contactid");
            JSONObject jobj = new JSONObject();
            caseid = hm.get("caseid").toString();
            KwlReturnObject kmsg = null;

            FileItem fileItem = (FileItem) hm.get("attachment");
            String filename = fileItem.getName();

            String docID = "";
            if (filename != null && filename != "") {
                if (fileItem.getSize() <= 10485760) { //limit 10 mb
                    kmsg = crmCustomerCaseService.uploadFile(fileItem, null, companyid, getServletContext());//Since document is uploaded by customer ,userid is null for uploadfile function
                    Docs doc = (Docs) kmsg.getEntityList().get(0);
                    docID = doc.getDocid();
                    jobj.put("docid", docID);
                    jobj.put("companyid", companyid);
                    jobj.put("map", "6");
                    jobj.put("refid", caseid);
                    crmCustomerCaseService.saveDocumentMapping(jobj);
                    crmCustomerCaseService.saveCustomerDocs(customerId, docID, caseid);
                }
            }
            request.setAttribute("casedetails", "true");
            request.setAttribute("caseid", caseid);
        } else {
            request.setAttribute("logout", "true");
        }
    } catch (Exception e) {
        logger.warn("Uploading Error");
        e.printStackTrace();
    }

    responseMessage = "usercases/redirect";

    return new ModelAndView(responseMessage, "model", model);
}

From source file:com.alkacon.opencms.excelimport.CmsResourceExcelImport.java

/**
 * Sets content from uploaded file.<p>
 * /* www  .j av a2 s .  co m*/
 * @param content the parameter value is only necessary for calling this method
 */
public void setParamExcelContent(String content) {

    // use parameter value
    if (content == null) {
        // do nothing   
    }

    // get the file item from the multipart request
    if (getMultiPartFileItems() != null) {
        Iterator i = getMultiPartFileItems().iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getFieldName().equals(PARAM_EXCEL_FILE)) {
                // found the file objectif (fi != null) {
                long size = fi.getSize();
                long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
                // check file size
                if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                    // file size is larger than maximum allowed file size, throw an error
                    //throw new CmsWorkplaceException();
                }
                m_excelContent = fi.get();
                m_excelName = fi.getName();
                fi.delete();
            } else {
                continue;
            }
        }
    }
}

From source file:com.corejsf.UploadRenderer.java

public void decode(FacesContext context, UIComponent component) {
    log.debug("**** decode =");
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId + UPLOAD);
    // check if file > maxSize allowed
    log.debug("clientId =" + clientId);
    log.debug("fileItem =" + item);
    // if (item!=null) log.debug("***UploadRender: fileItem size ="+ item.getSize());
    Long maxSize = (Long) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_SIZE_MAX");
    // RU - typo. Stanford agrees, so this should be FINR
    if (item != null && item.getSize() / 1000 > maxSize.intValue()) {
        ((ServletContext) external.getContext()).setAttribute("TEMP_FILEUPLOAD_SIZE",
                Long.valueOf(item.getSize() / 1000));
        ((EditableValueHolder) component).setSubmittedValue("SizeTooBig:" + item.getName());
        return;/*  w  w w  . j a  v  a2 s.c  o  m*/
    }

    Object target;
    ValueBinding binding = component.getValueBinding("target");
    if (binding != null)
        target = binding.getValue(context);
    else
        target = component.getAttributes().get("target");

    String repositoryPath = (String) ((ServletContext) external.getContext())
            .getAttribute("FILEUPLOAD_REPOSITORY_PATH");
    log.debug("****" + repositoryPath);
    if (target != null) {
        File dir = new File(repositoryPath + target.toString()); //directory where file would be saved
        if (!dir.exists())
            dir.mkdirs();
        if (item != null && !("").equals(item.getName())) {
            String fullname = item.getName();
            fullname = fullname.replace('\\', '/'); // replace c:\fullname to c:/fullname
            fullname = fullname.substring(fullname.lastIndexOf("/") + 1);
            int dot_index = fullname.lastIndexOf(".");
            String filename = "";
            if (dot_index < 0) {
                filename = fullname + "_" + (new Date()).getTime();
            } else {
                filename = fullname.substring(0, dot_index) + "_" + (new Date()).getTime()
                        + fullname.substring(dot_index);
            }
            File file = new File(dir.getPath() + "/" + filename);
            log.debug("**1. filename=" + file.getPath());
            try {
                //if (mediaIsValid) item.write(file);
                item.write(file);
                // change value so we can evoke the listener
                ((EditableValueHolder) component).setSubmittedValue(file.getPath());
            } catch (Exception ex) {
                throw new FacesException(ex);
            }
        }
    }
}

From source file:com.github.ikidou.handler.FormHandler.java

private List<FileEntity> getFileEntities(Map<String, Object> result, List<FileItem> fileItems)
        throws Exception {
    List<FileEntity> fileEntities = new ArrayList<>();

    for (FileItem fileItem : fileItems) {

        if (fileItem.isFormField()) {
            fileItem.getFieldName();/*  w  w w.j a  v  a 2s .c om*/
            result.put(fileItem.getFieldName(), fileItem.getString());
            if (!fileItem.isInMemory()) {
                fileItem.delete();
            }
        } else {
            FileEntity fileEntity = new FileEntity();
            fileEntity.name = fileItem.getName();
            fileEntity.contentType = fileItem.getContentType();
            fileEntity.size = fileItem.getSize();
            fileEntity.readableSize = FileSizeUtil.toReadable(fileItem.getSize());
            fileEntity.savePath = "Data/" + fileEntity.name;
            File file = new File(fileEntity.savePath);
            fileItem.write(file);
            fileEntities.add(fileEntity);
        }

    }

    return fileEntities;
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* ww  w  . j  a v  a2  s  .c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:com.krawler.spring.crm.caseModule.CrmCustomerCaseController.java

public ModelAndView saveCustomerCases(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, ServiceException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;/*from w  ww. j  av a  2 s  .c o m*/
    CrmCase cases = null;
    String responseMessage = "";
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    FileUploadHandler uh = new FileUploadHandler();
    HashMap hm = uh.getItems(request);
    Map model = new HashMap();

    try {

        String companyid = sessionHandlerImpl.getCompanyid(request);
        String customerId = (String) request.getSession().getAttribute("customerid");
        String contactId = (String) request.getSession().getAttribute("contactid");
        String caseOwnerID = crmCustomerCaseService.getCompanyCaseDefaultOwnerID(companyid);
        Integer operationCode = CrmPublisherHandler.ADDRECORDCODE;
        JSONObject jobj = new JSONObject();
        JSONObject jobj1 = new JSONObject();
        String id = java.util.UUID.randomUUID().toString();

        jobj.put("caseid", id);
        jobj.put("contactnameid", contactId);
        jobj.put("userid", caseOwnerID);
        jobj.put("caseownerid", caseOwnerID);
        jobj.put("subject", hm.get("subject"));
        jobj.put("description", hm.get("description"));
        jobj.put("companyid", companyid);
        jobj.put("createdon", System.currentTimeMillis());
        jobj.put("updatedon", System.currentTimeMillis());
        jobj.put("casecreatedby", contactId);
        jobj.put("createdbyflag", "1");

        kmsg = crmCustomerCaseService.addCases(jobj);
        cases = (CrmCase) kmsg.getEntityList().get(0);

        try {
            FileItem fileItem = (FileItem) hm.get("attachment");
            String filename = fileItem.getName();
            String docID = "";
            if (filename != null && filename != "") {
                if (fileItem.getSize() <= 10485760) { //limit 10 mb
                    kmsg = crmCustomerCaseService.uploadFile(fileItem, null, companyid, getServletContext());//Since document is uploaded by customer ,userid is null for uploadfile function
                    Docs doc = (Docs) kmsg.getEntityList().get(0);
                    docID = doc.getDocid();
                    jobj1.put("docid", docID);
                    jobj1.put("companyid", companyid);
                    jobj1.put("id", id);
                    jobj1.put("map", "6");
                    jobj1.put("refid", id);
                    crmCustomerCaseService.saveDocumentMapping(jobj1);
                    crmCustomerCaseService.saveCustomerDocs(customerId, docID, id);
                }
            }
        } catch (Exception e) {
            logger.warn("Attachment upload failed with Customer case :" + e.getMessage());
        }

        myjobj.put("success", true);
        myjobj.put("ID", cases.getCaseid());
        myjobj.put("createdon", jobj.optLong("createdon"));
        txnManager.commit(status);

        JSONObject cometObj = jobj;
        if (!StringUtil.isNullObject(cases)) {
            if (!StringUtil.isNullObject(cases.getCreatedon())) {
                cometObj.put("createdon", cases.getCreatedonGMT());
            }
        }
        //publishCasesModuleInformation(request, cometObj, operationCode, companyid, caseOwnerID);
        request.setAttribute("caselist", "true");
        responseMessage = "usercases/redirect";

    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView(responseMessage, "model", model);
}

From source file:de.fhg.fokus.openride.services.profile.ProfileService.java

@POST
@Path("picture/")
@Produces("text/json")
public Response postPicture(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("postPicture start");

    boolean success = false;

    //String profilePicturesPath = "C:\\OpenRide\\pictures\\profile";
    String profilePicturesPath = "../OpenRideWeb/img/profile/default";

    //TODO/*from   w  ww  .ja  va 2  s .  com*/
    //String imagePath = getServletConfig().getInitParameter("imagePath");

    // FIXME: The following try/catch may be removed for production deployments:
    /*try {
    if (java.net.InetAddress.getLocalHost().getHostName().equals("elan-tku-r2032.fokus.fraunhofer.de")) {
        profilePicturesPath = "/mnt/windows/OpenRide/pictures/profile";
    }
    else if (java.net.InetAddress.getLocalHost().getHostName().equals("robusta2.fokus.fraunhofer.de")) {
        profilePicturesPath = "/usr/lib/openride/pictures/profile";
    }
    } catch (UnknownHostException ex) {
    }*/

    int picSize = 125;
    int picThumbSize = 60;

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    if (ServletFileUpload.isMultipartContent(con)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(con);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (items != null) {
            Iterator<FileItem> iter = items.iterator();

            CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
            String uploadedFileName = c.getCustNickname() + "_" + c.getCustId();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {

                    try {
                        BufferedImage uploadedPicture = ImageIO.read(item.getInputStream());

                        int newWidth, newHeight;
                        int xPos, yPos;
                        float ratio = (float) uploadedPicture.getHeight() / (float) uploadedPicture.getWidth();

                        // Resize for "large" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        Image resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picSize - newWidth) / 2);
                        yPos = Math.round((picSize - newHeight) / 2);
                        BufferedImage bim = new BufferedImage(picSize, picSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picSize, picSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        File outputPicture = new File(profilePicturesPath, uploadedFileName + ".jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                        // Resize again for "thumb" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picThumbSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picThumbSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picThumbSize - newWidth) / 2);
                        yPos = Math.round((picThumbSize - newHeight) / 2);
                        bim = new BufferedImage(picThumbSize, picThumbSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picThumbSize, picThumbSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        outputPicture = new File(profilePicturesPath, uploadedFileName + "_thumb.jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("File upload / resize unsuccessful.");
                    }
                    success = true;
                }
            }
        }
    }

    if (success) {

        // TODO: Perhaps introduce a redirection target as a parameter to the putProfile method and redirect to that URL (code 301/302) instead of just doing nothing.
        return null;

        /*
        try {
        String referer = con.getHeader("HTTP_REFERER");
        System.out.println("putPicture: Referer: " + referer);
        if (referer != null)
        return Response.status(Response.Status.SEE_OTHER).contentLocation(new URI(referer)).build();
        else
        return Response.ok().build();
        } catch (URISyntaxException ex) {
        Logger.getLogger(ProfileService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).build();
        }
         */
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}