Example usage for javax.servlet.http Part getSize

List of usage examples for javax.servlet.http Part getSize

Introduction

In this page you can find the example usage for javax.servlet.http Part getSize.

Prototype

public long getSize();

Source Link

Document

Returns the size of this fille.

Usage

From source file:lk.studysmart.apps.BrainTeaserFileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww  w  .  ja v  a  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");

    user = (User) request.getSession().getAttribute("user");
    //Get information from tha frontend of file upload
    final Part filePart = request.getPart("file");
    final String fileName = request.getParameter("filename");
    final String description = request.getParameter("description");

    InputStream filecontent = filePart.getInputStream();

    byte[] bytes = IOUtils.readFully(filecontent, Integer.valueOf(Long.toString(filePart.getSize())));

    Subject subject = em.find(Subject.class, request.getParameter("subject"));

    //Set attribute values to object 
    Internalresources resource = new Internalresources();
    resource.setUser(user);
    resource.setSubject(subject);
    resource.setFilename(fileName);
    resource.setDescription(description);
    resource.setBlob(bytes);

    try {
        utx.begin();
        em.persist(resource);
        utx.commit();
    } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
            | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
        Logger.getLogger(BrainTeaserFileUpload.class.getName()).log(Level.SEVERE, null, ex);
        response.getWriter().write("Error: " + ex.getLocalizedMessage());
    }
    //Redirect page to the teacher's VLE main interface
    response.sendRedirect("teachVLEMUI.jsp?msg=File Uploaded");
}

From source file:paquete.producto.Main.java

/**
 * Almacena la imagen indicada en el input "imagen" del formulario
 * dentro de la carpeta indicada en la constante SAVE_DIR, generando un
 * nombre nuevo para el archivo en funcin de una codificacin MD5
 * /*from  ww  w  .j a v a2 s  . c om*/
 * @param request
 * @return Nombre generado para la imagen o null si no se ha enviado ningn
 * archivo
 */
private String saveImagen(HttpServletRequest request) {
    //Crear la ruta completa donde se guardarn las imgenes
    String appPath = request.getServletContext().getRealPath("");
    String savePath = appPath + File.separator + SAVE_DIR;
    logger.fine("Save path = " + savePath);

    //Crear la carpeta si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin
    //  del tiempo y una palabra secreta. 
    //  Se utiliza una codificacin de este tipo para que se dificulte la 
    //  localizacin no permitida de las imgenes
    String secret = "W8fQAP9X";
    long time = Calendar.getInstance().getTimeInMillis();
    //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera 
    //  org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto)
    String fileName = DigestUtils.md5Hex(secret + time);

    try {
        //Obtener los datos enviados desde el input "photoFileName" del formulario
        Part filePart = request.getPart("imagen");
        String fullPathFile = savePath + File.separator + fileName;
        //Guardar la imagen en la ruta y nombre indicados
        if (filePart.getSize() > 0) {
            filePart.write(fullPathFile);
            logger.fine("Saved file: " + fullPathFile);
            return fileName;
        } else {
            return null;
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalStateException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServletException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.ahm.fileupload.FileController.java

public String processUpload(Part fileUpload) throws Exception {
    String fileSaveData = null;/*w  ww  .j a v  a 2 s  .c  o m*/
    try {
        if (fileUpload.getSize() > 0) {

            String submittedFileName = this.getFileName(fileUpload);
            if (checkFileType(submittedFileName)) {

                if (fileUpload.getSize() > this.limit_max_size) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(""));
                } else {
                    String currentFileName = submittedFileName;
                    String extension = currentFileName.substring(currentFileName.lastIndexOf("."),
                            currentFileName.length());
                    Long nameRandom = Calendar.getInstance().getTimeInMillis();

                    String newFileName = nameRandom + extension;

                    fileSaveData = newFileName;

                    String fileSavePath = FacesContext.getCurrentInstance().getExternalContext()
                            .getRealPath(this.path_to);
                    System.out.println("Save path " + fileSavePath);
                    //System.out.println("Save path " + currentFileName+" ext: "+extension);

                    try {
                        byte[] fileContent = new byte[(int) fileUpload.getSize()];
                        InputStream in = fileUpload.getInputStream();
                        in.read(fileContent);
                        File fileToCreate = new File(fileSavePath, newFileName);
                        File folder = new File(fileSavePath);
                        if (!folder.exists()) {
                            folder.mkdir();
                        }

                        FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
                        fileOutStream.write(fileContent);
                        fileOutStream.flush();
                        fileOutStream.close();
                        fileSaveData = newFileName;
                    } catch (Exception e) {
                        fileSaveData = null;
                        throw e;
                    }
                }
            } else {
                fileSaveData = null;
                System.out.println("No tiene formato valido");
            }
        } else {
            System.out.println("No tiene nada");
        }

    } catch (Exception e) {
        fileSaveData = null;
        throw e;
    }

    return fileSaveData;
}

From source file:catalogo.Main.java

/**
 * Almacena la imagen indicada en el input "photoFileName" del formulario
 * dentro de la carpeta indicada en la constante SAVE_DIR, generando un
 * nombre nuevo para el archivo en funcin de una codificacin MD5
 * /*w  ww . j a  v a 2  s . c om*/
 * @param request
 * @return Nombre generado para la imagen o null si no se ha enviado ningn
 * archivo
 */
private String savePhotoFile(HttpServletRequest request) {
    //Crear la ruta completa donde se guardarn las imgenes
    String appPath = request.getServletContext().getRealPath("");
    String savePath = appPath + File.separator + SAVE_DIR;
    logger.fine("Save path = " + savePath);

    //Crear la carpeta si no existe
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    //Crear un nombre para la imagen utilizando un cdigo MD5 en funcin
    //  del tiempo y una palabra secreta. 
    //  Se utiliza una codificacin de este tipo para que se dificulte la 
    //  localizacin no permitida de las imgenes
    String secret = "W8fQAP9X";
    long time = Calendar.getInstance().getTimeInMillis();
    //Para generar el cdigo MD5 se usa la clase DigestUtils de la librera 
    //  org.apache.commons.codec (se incluye en la carpeta 'libs' del proyecto)
    String fileName = DigestUtils.md5Hex(secret + time);

    try {
        //Obtener los datos enviados desde el input "photoFileName" del formulario
        Part filePart = request.getPart("photoFileName");
        String fullPathFile = savePath + File.separator + fileName;
        //Guardar la imagen en la ruta y nombre indicados
        if (filePart.getSize() > 0) {
            filePart.write(fullPathFile);
            logger.fine("Saved file: " + fullPathFile);
            return fileName;
        } else {
            return null;
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalStateException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServletException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:net.voidfunction.rm.master.AdminServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Date", HTTPUtils.getServerTime(0));
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    Part uploadFile = request.getPart("uploadfile");
    if (uploadFile == null)
        throw new ServletException("Uploaded file is null.");

    // Get some info about the file
    String filename = getFilename(uploadFile);
    String contentType = uploadFile.getContentType();
    long size = uploadFile.getSize();
    byte[] hash = FileUtils.sha256Hash(uploadFile.getInputStream());

    // Create a new file object, add it to the database, and store data
    RMFile newFile = new RMFile(filename, contentType, size, hash);
    node.getFileRepository().addFile(newFile, uploadFile.getInputStream());

    // Output data for interested parties
    Template tpl = new Template(new File(templateDir + "uploadsuccess.tpl"));
    tpl.assign("FILENAME", filename);
    tpl.assign("SIZE", String.valueOf(size));
    tpl.assign("TYPE", contentType);
    tpl.assign("HASH", Hex.encodeHexString(hash));
    tpl.assign("FILEID", newFile.getId());
    tpl.parse("main");
    response.getWriter().print(tpl.out());

    // Delete temp file
    uploadFile.delete();/* w  w w.  jav a  2 s .co  m*/

    // Log
    node.getLog().info("New file added (via web): " + newFile.getId() + " (" + newFile.getName() + ")");
}

From source file:com.imagelake.uploads.Servlet_Upload.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Date d = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
    String date = sm.format(d);//from   www.  java  2s.co m

    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    UserDAOImp udi = new UserDAOImp();
    // gets values of text fields
    PrintWriter out = response.getWriter();

    String cat, imgtit, imgname, dominate, price, dimention, col1, col2, col3, col4, col5, col6, col7, col8,
            col9, size_string, uid;
    System.out.println("server name====" + request.getServerName());

    uid = request.getParameter("uid");
    imgname = request.getParameter("imgname");
    imgtit = request.getParameter("tit");
    cat = request.getParameter("cat");
    dimention = request.getParameter("dimention");
    dominate = request.getParameter("dominate");
    col1 = request.getParameter("col-1");
    col2 = request.getParameter("col-2");
    col3 = request.getParameter("col-3");
    col4 = request.getParameter("col-4");
    col5 = request.getParameter("col-5");
    col6 = request.getParameter("col-6");
    col7 = request.getParameter("col-7");
    col8 = request.getParameter("col-8");
    col9 = request.getParameter("col-9");
    size_string = request.getParameter("size");
    long size = 0;

    System.out.println(cat + " " + imgname + " " + col1 + " " + col2 + " " + col3 + " " + col4 + " " + col5
            + " " + col6 + " " + col7 + " " + col8 + " " + col9 + " //" + dominate + " " + size_string);
    System.out.println(request.getParameter("tit") + "bbbbb" + request.getParameter("cat"));
    InputStream inputStream = null; // input stream of the upload file

    System.out.println("woooooooooo" + imgtit.trim() + "hooooooooo");

    if (imgtit.equals("") || imgtit.equals(null) || cat.equals("") || cat.equals(null) || cat.equals("0")
            || dimention.equals("") || dimention.equals(null) && dominate.equals("")
            || dominate.equals(null) && col1.equals("") || col1.equals(null) && col2.equals("")
            || col2.equals(null) && col3.equals("") || col3.equals(null) && col4.equals("")
            || col4.equals(null) && col5.equals("") && col5.equals(null) && col6.equals("")
            || col6.equals(null) && col7.equals("") || col7.equals(null) && col8.equals("")
            || col8.equals(null) && col9.equals("") || col9.equals(null)) {
        System.out.println("error");

        out.write("error");
    } else {

        // obtains the upload file part in this multipart request 
        try {
            Part filePart = request.getPart("photo");

            if (filePart != null) {
                // prints out some information for debugging
                System.out.println("NAME:" + filePart.getName());
                System.out.println(filePart.getSize());
                size = filePart.getSize();
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
                System.out.println(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Connection conn = null; // connection to the database
        String message = null; // message will be sent back to client
        String fileName = null;
        try {

            // gets absolute path of the web application
            String applicationPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

            // creates the save directory if it does not exists
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
            System.out.println("Upload File Directory2=" + fileSaveDir.getAbsolutePath() + "/" + imgname);

            //Get all the parts from request and write it to the file on server
            for (Part part : request.getParts()) {
                fileName = getFileName(part);
                if (!fileName.equals(null) || !fileName.equals("")) {
                    try {
                        part.write(uploadFilePath + File.separator + fileName);
                    } catch (Exception e) {
                        break;
                    }
                }

            }

            //GlassFish File Upload

            System.out.println(inputStream);

            if (inputStream != null) {

                // int id=new ImagesDAOImp().checkImagesId(dominate, col1, col2, col3, col4, col5, col6, col7, col8, col9);
                //   if(id==0){
                boolean sliceImage = new CreateImages().sliceImages(col1, col2, col3, col4, col5, col6, col7,
                        col8, col9, dominate, imgname, dimention, imgtit, cat, uid, date);
                if (sliceImage) {
                    AdminNotification a = new AdminNotification();
                    a.setUser_id(Integer.parseInt(uid));
                    a.setDate(timeStamp);

                    a.setShow(1);
                    a.setType(1);
                    String not = "New Image has uploaded by " + udi.getUn(Integer.parseInt(uid));
                    a.setNotification(not);

                    int an = new AdminNotificationDAOImp().insertNotificaation(a);
                    System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an);

                    boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.listAdminsIDs(), an,
                            1);
                    if (kl) {
                        out.write("ok");
                    } else {
                        System.out.println("error in sliceimage");
                        out.write("error");
                    }
                } else {
                    System.out.println("error in sliceimage");
                    out.write("error");
                }
                // }
                /*else{
                              System.out.println("error in id");
                        out.write("error");
                    }*/

            }

            // sends the statement to the database server

        } catch (Exception ex) {
            message = "ERROR: " + ex.getMessage();
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                // closes the database connection
                try {
                    conn.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }

        }

    }

    //out.write("ok");
    //else code          

}

From source file:cn.mypandora.controller.MyUpload.java

/**
 * @param part//from  w w w.j  a  v a2s .com
 * @return void
 * @Title: upload
 * @Description: 
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(@RequestParam("myFile") Part part, @RequestParam("choosePath") String choosePath) {
    try {
        /* ? */
        /* ? */
        ResourceBundle resourceBundle = ResourceBundle.getBundle("upload");
        String savePath = resourceBundle.getString(choosePath != null ? choosePath : "defaultPath")
                + getFileName(part);
        // String webRootPath = request.getServletContext().getRealPath("/upload");
        String webRootPath = System.getProperty("contentPath");
        part.write(webRootPath + savePath);

        // ??
        UploadFile file = new UploadFile();
        file.setFileSize(part.getSize());
        file.setFileName(getFileName(part));
        file.setSaveName(getFileName(part));
        file.setFileType(1);
        file.setSavePath(savePath);
        file.setCreateTime(new Timestamp(1234567890L));
        file.setUpdateTime(new Timestamp(1234567891L));
        baseUploadService.saveFile(file);

        //            return file;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:ips1ap101.lib.core.jsf.JSF.java

public static boolean isValidPart(Object value) {
    if (value instanceof Part) {
        Part part = (Part) value;
        return part.getSize() > 0 && StringUtils.isNotBlank(getPartFileName(part));
    }//from  w  ww.j  ava2  s . c  o  m
    return false;
}

From source file:com.contact.ContactController.java

@RequestMapping(method = RequestMethod.POST)
public String create(@Valid Contact contact, BindingResult bindingResult, Model uiModel,
        HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale,
        @RequestParam(value = "file", required = false) Part file) {
    logger.info("Creating contact");
    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("message",
                new Message("error", messageSource.getMessage("contact_save_fail", new Object[] {}, locale)));
        uiModel.addAttribute("contact", contact);

        return "contacts/create";
    }//w w  w  .java  2 s. co m

    uiModel.asMap().clear();
    redirectAttributes.addFlashAttribute("message",
            new Message("success", messageSource.getMessage("contact_save_success", new Object[] {}, locale)));

    logger.info("Contact id: " + contact.getId());

    // Process upload file
    if (file != null) {
        logger.info("File name: " + file.getName());
        logger.info("File size: " + file.getSize());
        logger.info("File content type: " + file.getContentType());
        byte[] fileContent = null;
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null)
                logger.info("File inputstream is null");
            fileContent = IOUtils.toByteArray(inputStream);
            contact.setPhoto(fileContent);
        } catch (IOException ex) {
            logger.error("Error saving uploaded file");
        }
        contact.setPhoto(fileContent);
    }

    contactService.save(contact);

    return "redirect:/contacts/";
}

From source file:Controllers.MurController.java

@RequestMapping(value = "{path}/ajoutStatut", method = RequestMethod.POST)
public ModelAndView ajoutStatut(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String path) throws Exception {

    ModelAndView mv;/*from   w ww .ja  v  a  2s  .c  o m*/

    // Rcupration de la session
    HttpSession session = request.getSession(false);

    // Accs sans tre connect
    if (session == null || session.getAttribute("idUtilisateur") == null) {
        mv = new ModelAndView("connexion");
        mv.addObject("inscriptionMessage", "Veuillez vous connecter pour accder  cette page");
        return mv;
    }
    Part p = request.getPart("file");
    // Rcupration de l'id de l'utilisateur courant
    int idUtilisateur = (int) session.getAttribute("idUtilisateur");

    int idPersonne = Integer.parseInt(request.getParameter("idPersonne"));

    // Rcupration du texte du statut post
    String statut = request.getParameter("statut");

    // Ajout du statut
    int idStatut = 0;
    if (idPersonne == idUtilisateur) {
        idStatut = murService.ajoutStatut(idUtilisateur, statut);
    } else {
        idStatut = murService.posterStatut(idUtilisateur, idPersonne, statut);
    }

    if (p.getSize() != 0 && idStatut != 0) {
        fichierService.ajoutFichier(p, idStatut);
    }

    mv = getRedirect(path, idPersonne, idStatut);
    return mv;
}