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:org.sherlok.FileBased.java

/**
 * PUTs (writes) this resource to disk./* w ww.j a va  2  s.c o  m*/
 * 
 * @param path
 *            the path where to write this resource to
 * @param part
 *            holds the resource file itself
 */
public static void putResource(String path, Part part) throws SherlokException {

    validateArgument(!path.contains(".."), "path cannot contain '..'");
    validateArgument(part.getSize() < MAX_UPLOAD_SIZE,
            "file too large, max allowed " + MAX_UPLOAD_SIZE + " bytes");
    validateArgument(part.getSize() > 0, "file is empty");

    File outFile = new File(RUTA_RESOURCES_PATH, path);
    outFile.getParentFile().mkdirs();
    try {
        FileUtils.copyInputStreamToFile(part.getInputStream(), outFile);
    } catch (IOException e) {
        new SherlokException("could not upload file to", path);
    }
}

From source file:controllers.IndexServlet.java

private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    response.setContentType("text/plain");

    try {/*www. ja  v  a 2  s  . com*/
        Part httpPostedFile = request.getPart("file");

        String fileName = "";
        for (String content : httpPostedFile.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                fileName = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }

        long curSize = httpPostedFile.getSize();
        if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0) {
            writer.write("{ \"error\": \"File size is incorrect\"}");
            return;
        }

        String curExt = FileUtility.GetFileExtension(fileName);
        if (!DocumentManager.GetFileExts().contains(curExt)) {
            writer.write("{ \"error\": \"File type is not supported\"}");
            return;
        }

        InputStream fileStream = httpPostedFile.getInputStream();

        fileName = DocumentManager.GetCorrectName(fileName);
        String fileStoragePath = DocumentManager.StoragePath(fileName, null);

        File file = new File(fileStoragePath);

        try (FileOutputStream out = new FileOutputStream(file)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = fileStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.flush();
        }

        writer.write("{ \"filename\": \"" + fileName + "\"}");

    } catch (IOException | ServletException e) {
        writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
    }
}

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 {/* www. ja  v  a2  s . c  o  m*/
        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:org.sonar.server.ws.ServletRequest.java

@Override
@CheckForNull/*ww w .  j  a  va2 s.c  o  m*/
public Part readPart(String key) {
    try {
        if (!isMultipartContent()) {
            return null;
        }
        javax.servlet.http.Part part = source.getPart(key);
        if (part == null || part.getSize() == 0) {
            return null;
        }
        return new PartImpl(part.getInputStream(), part.getSubmittedFileName());
    } catch (Exception e) {
        throw new IllegalStateException("Can't read file part", e);
    }
}

From source file:beans.DecryptFileBean.java

public void validateFile(FacesContext ctx, UIComponent comp, Object value) {
    if (getUser() != null) {
        Part file = (Part) value;
        if (file != null) {
            status = "";
            if (file.getSize() > 1024) {
                status += "- File too big.\n";
            }//from   www. j av a  2s . co m
            if (!"text/plain".equals(file.getContentType())) {
                status += "- " + file.getContentType() + " content was found in " + file.getName()
                        + ". Expected text/plain. Please select a text file.";
            }
        }
    } else {
        status = "You are not logged in.";
    }
}

From source file:org.mhi.servlets.ImageUpload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    // Service Class for DB - Actions
    ServiceQuery query = new ServiceQuery();
    ServiceUpdate update = new ServiceUpdate();

    String imgName = request.getParameter("name");
    String imgDesc = request.getParameter("desc");
    String imgCat = request.getParameter("category");
    String fileSize = null;//from ww  w .  j  a va  2 s.  c  o m
    String fileName = null;
    String contentType = null;
    String[] parts = null;

    InputStream inputStream = null; // input stream of the upload file

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

    if (filePart != null) {
        // Fill up Information extract from File
        fileSize = "" + filePart.getSize();
        parts = filePart.getSubmittedFileName().split("\\.");
        contentType = filePart.getContentType();

        // obtains input stream of the upload file
        inputStream = filePart.getInputStream();

        // new Image
        Images img = new Images();
        // Set Parameters
        img.setFileName(imgName + "." + parts[1]);
        img.setName(imgName);
        img.setDescription(imgDesc);
        img.setFileBlob(IOUtils.toByteArray(inputStream));
        img.setFileSize(fileSize);
        img.setcTyp(contentType);
        // Relationship to Category
        ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat));
        img.setCategory(cat);
        // Persist to Database
        update.insertImage(img);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload");

}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    try {/* w w w. j ava  2s .com*/

        //servlet?Partnull
        //9.0.4.v20130625 ??
        System.out.println(req.getParameter("name"));

        //?Part
        System.out.println("\n\n==========file1");
        Part file1Part = req.getPart("file1"); //?? ?Part
        InputStream file1PartInputStream = file1Part.getInputStream();
        System.out.println(IOUtils.toString(file1PartInputStream));
        file1PartInputStream.close();

        // ??
        System.out.println("\n\n==========file2");
        Part file2Part = req.getPart("file2");
        InputStream file2PartInputStream = file2Part.getInputStream();
        System.out.println(IOUtils.toString(file2PartInputStream));
        file2PartInputStream.close();

        System.out.println("\n\n==========parameter name");
        //????
        System.out.println(IOUtils.toString(req.getPart("name").getInputStream()));
        //Part??? jettyparameters??
        System.out.println(req.getParameter("name"));

        //?? ? req.getInputStream(); ??

        System.out.println("\n\n=============all part");
        for (Part part : req.getParts()) {
            System.out.println("\n\n=========name:::" + part.getName());
            System.out.println("=========size:::" + part.getSize());
            System.out.println("=========content-type:::" + part.getContentType());
            System.out
                    .println("=========header content-disposition:::" + part.getHeader("content-disposition"));
            System.out.println("=========file name:::" + getFileName(part));
            InputStream partInputStream = part.getInputStream();
            System.out.println("=========value:::" + IOUtils.toString(partInputStream));

            //
            partInputStream.close();
            // ? ? ?
            part.delete();

        }

    } catch (IllegalStateException ise) {
        //
        ise.printStackTrace();
        String errorMsg = ise.getMessage();
        if (errorMsg.contains("Request exceeds maxRequestSize")) {
            //?
        } else if (errorMsg.contains("Multipart Mime part file1 exceeds max filesize")) {
            //? ??
        } else {
            //
        }
    }

}

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

@RequestMapping(value = "/up", method = RequestMethod.POST)
public void up(@RequestParam("FileDate") Part part) {
    UploadFile file = new UploadFile();
    file.setFileSize(part.getSize());

}

From source file:com.ge.apm.service.asset.AttachmentFileService.java

public Integer uploadFile(Part file) {
    Integer returnId = 0;//from  ww w  .  j  a  v a 2  s . c om
    try {
        returnId = fileUploaddao.saveUploadFile(file.getInputStream(),
                Integer.valueOf(String.valueOf(file.getSize())), file.getSubmittedFileName());
    } catch (SQLException | IOException ex) {
        WebUtil.addErrorMessage(WebUtil.getMessage("fileTransFail"));
        Logger.getLogger(AttachmentFileService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return returnId;
}

From source file:AddPost.java

/**
 * metodo usato per gestire il caso di upload di file multipli da 
 * parte del'utente su un singolo post, siccome la libreria 
 * utilizzata non gestiva questo particolare caso.
 * @throws IOException//  w w  w  .  j  a v a  2  s .  co  m
 * @throws ServletException
 * @throws SQLException 
 */
private void getFiles() throws IOException, ServletException, SQLException {
    Collection<Part> p = mReq.getParts();
    for (Part part : p) {
        if (part.getName().equals("post")) {
            //
        } else {
            if (part.getSize() > 1024 * 1024 * 10) {
                error++;
            } else {
                String path = mReq.getServletContext().getRealPath("/");
                String name = part.getSubmittedFileName();
                int i;
                if (isInGroupFiles(name)) {
                    for (i = 1; isInGroupFiles("(" + i + ")" + name); i++)
                        ;
                    name = "(" + i + ")" + name;
                }

                //Hotfixies for absoluth paths

                //IE
                if (name.contains("\\")) {
                    name = name.substring(name.lastIndexOf("\\"));
                }

                //somthing else, never encountered
                if (name.contains("/")) {
                    name = name.substring(name.lastIndexOf("/"));
                }

                dbm.newFile(dbm.getIdFromUser(user), groupid, name);

                File outputFile = new File(path + "/files/" + groupid + "/" + name);
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                }
                if (!outputFile.isDirectory()) {
                    InputStream finput = new BufferedInputStream(part.getInputStream());
                    OutputStream foutput = new BufferedOutputStream(new FileOutputStream(outputFile));

                    byte[] buffer = new byte[1024 * 500];
                    int bytes_letti = 0;
                    while ((bytes_letti = finput.read(buffer)) > 0) {
                        foutput.write(buffer, 0, bytes_letti);
                    }
                    finput.close();
                    foutput.close();
                }
            }
        }

    }

}