Example usage for javax.servlet.http Part write

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

Introduction

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

Prototype

public void write(String fileName) throws IOException;

Source Link

Document

A convenience method to write this uploaded item to disk.

Usage

From source file:org.primefaces.model.NativeUploadedFile.java

@Override
public void write(String filePath) throws Exception {
    String validFilePath = FileUploadUtils.getValidFilePath(filePath);

    if (parts != null) {
        for (int i = 0; i < parts.size(); i++) {
            Part p = parts.get(i);
            p.write(validFilePath);
        }//w  w w. j  ava2  s .  c om
    } else {
        part.write(validFilePath);
    }
}

From source file:com.shoylpik.controller.AddProduct.java

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

    String SAVE_DIRECTORY = "shoylpik_images";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();/* ww  w.j a  v a2s .com*/
    }

    System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        System.out.println("fileName: " + fileName);
        part.write(savePath + File.separator + fileName);
    }

    try {
        System.out.println("savePath : " + savePath);
        String imageName = request.getParameter("IPimage");
        System.out.println("imageName: " + imageName);
        Part filePart = request.getPart("IPimage");
        InputStream imageInputStream = filePart.getInputStream();

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(imageName);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        String fullImagePath = savePath + File.separator + imageName;
        File file = new File(fullImagePath);
        System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {

        } else {
            System.out.println("Inside else");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {

            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                System.out.println("Inside while");
                FileItem item = (FileItem) items.iterator();
                item.write(file);
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

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
 * /* w w w.j av a 2 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: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
 * /*from w w w.  j a v a2  s  .co m*/
 * @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: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   w  ww .j a  v  a 2s  .c  om*/

    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:de.unirostock.sems.caroweb.Converter.java

private void runPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Path STORAGE = CaRoWebutils.getStorage(getServletContext());

    String[] req = request.getRequestURI().substring(request.getContextPath().length()).split("/");

    if (req == null || req.length < 2) {
        error(request, response, "do not know what to do");
        return;/*from  w w  w.  j a v a2s. com*/
    }

    if (req.length > 2 && req[1].equals("checkout")) {
        checkout(request, response, STORAGE, req[2]);
        return;
    }

    if (!req[1].equals("caro") && !req[1].equals("roca")) {
        error(request, response, "do not know what to do");
        return;
    }

    File tmp = File.createTempFile("container", "upload");
    File out = File.createTempFile("container", "converted");
    out.delete();
    // System.out.println (Arrays.toString (req));
    Part filePart = request.getPart("container");
    String uploadedName = null;
    if (filePart != null) {
        uploadedName = extractFileName(filePart);
        if (uploadedName == null)
            uploadedName = "container";

        filePart.write(tmp.getAbsolutePath());
    } else {
        error(request, response, "no file supplied");
        return;
    }

    run(request, response, uploadedName, req, tmp, out, STORAGE);
}

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

/**
 * @param part/* w ww  . ja v a 2s .  c  o m*/
 * @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:nz.net.paulo.FileUploadHandler.java

@Override
public void write(HttpServletResponse response) throws IOException {
    if (!rp.isMultiPart()) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }//from  w w  w.j a v a  2s. c o  m
    response.setContentType("application/json");
    JSONArray jsonArray = new JSONArray();
    String fileName = extractFileName(rp.getContentDisposition());
    Date lastModifiedDate = extractLastModifiedDate(rp.getContentDisposition());

    try {
        // we write all the parts to the temp dir...
        for (Part part : rp.getParts()) {
            if (StringUtils.isBlank(fileName)) {
                String partContentDisposition = part.getHeader("content-disposition");
                fileName = extractFileName(partContentDisposition);
                lastModifiedDate = extractLastModifiedDate(partContentDisposition);
            }
            String filePath = getFullFilePath(fileName);
            System.out.println("FilePath: " + filePath);
            part.write(filePath);
            if (isFilePart()) {
                File tempFile = new File(filePath);
                File partFile = rp.getPart(fileName);
                if (partFile.exists()) {
                    if (partFile.lastModified() != lastModifiedDate.getTime()) {
                        partFile.delete();
                        tempFile.delete();
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "The file appears to have been modified since the last upload. Please try again.");
                        return;
                    }
                    partFile = mergeFiles(partFile, tempFile);
                } else {
                    tempFile.renameTo(partFile);
                }
                partFile.setLastModified(lastModifiedDate.getTime());
                if (partFile.length() == getFileSize(rp.getContentRange())) {
                    File finalFile = rp.getFileInUploadDir(fileName);
                    partFile.renameTo(finalFile);
                }
            }
            File mainFile = rp.getFileInUploadDir(fileName);
            if (mainFile.exists()) {
                jsonArray.put(getFileJson(mainFile.getName(), mainFile.length()));
            }
        }
        String responseString = "{\"files\": " + jsonArray.toString() + "}";
        try (PrintWriter writer = response.getWriter()) {
            writer.write(responseString);
        }
    } catch (IllegalStateException | ServletException e) {
        throw new IOException(e);
    }

}

From source file:rzd.vivc.documentexamination.service.FileSavingToDiskService.java

@Override
public void saveUploadedFile(DocumentForm document) throws IOException {
    Part file = document.getFile();

    if (file == null || file.getSize() < 0 || file.getSubmittedFileName().isEmpty()) {
        //?    ,  ? ? ? 
    } else {/*w w w  .j  av a 2 s .com*/
        String address = "C:" + File.separator + File.separator + "documents" + File.separator;
        String name = file.getSubmittedFileName();
        while ((new File(address + name)).exists()) {
            String[] split = name.split("\\.");
            name = split[split.length - 2] + UUID.randomUUID().toString() + "." + split[split.length - 1];
        }
        file.write(address + name);
        document.setFileName(name);
    }
}

From source file:com.rubinefocus.admin.servlet.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  ww  w .  ja va 2s  .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 {
    //processRequest(request, response);
    try {
        PrintWriter out = response.getWriter();

        File f = new File(this.getServletContext().getRealPath("/admin/assets/images/adminPic"));
        String savePath = f.getPath();
        savePath = savePath.replace("%20", " ");
        savePath = savePath.replace("build", "");
        String fileName = "";

        for (Part part : request.getParts()) {
            fileName = extractFileName(part);
            fileName = fileName.replace(" ", "");
            fileName = fileName.replace("-", "");
            fileName = fileName.replace(":", "");

            File file = new File(savePath + "/" + fileName);
            if (file.exists()) {
                String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
                String ext = FilenameUtils.getExtension(fileName);
                fileName = fileNameWithOutExt + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date())
                        + "." + ext;
                fileName = fileName.replace(" ", "");
                fileName = fileName.replace("-", "");
                fileName = fileName.replace(":", "");
                part.write(savePath + File.separator + fileName);
            } else {

                part.write(savePath + File.separator + fileName);
            }

        }

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