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:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//w  w  w . j a  v a 2 s  .  co  m
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    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:\\Windows\\Temp\\"));

    // 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();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // 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>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("--- BEGIN DOPOST ---");

    request.setCharacterEncoding("UTF-8");
    request.setAttribute(RETVAL, "0");
    request.setAttribute(FILEURL, "");
    request.setAttribute(ERRORMESSAGE, "");
    String newName = "";
    String hash = "";
    // ???//from   www.  j a v  a2  s  . co  m
    VWBContext context = VWBContext.createContext(request, VWBCommand.ATTACH, null);
    rb = context.getBundle("templates/default");

    if (!context.getVWBSession().isAuthenticated()) {
        request.setAttribute(RETVAL, "212");
        request.setAttribute(ERRORMESSAGE, rb.getString("uploader.nopermission"));
    } else {
        if (enabled) {
            try {
                Map<String, Object> fields = parseFileItem(request);

                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                long fileSize = uplFile.getSize();
                InputStream in = uplFile.getInputStream();

                if (fileSize == 0 || in == null) {
                    if (debug)
                        log.error("The upload file size is 0 or inputstream is null!");
                    request.setAttribute(RETVAL, "211");
                    request.setAttribute(ERRORMESSAGE, rb.getString("error.doc.zerolength"));
                } else {
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("title", fileName);
                    hashMap.put("summary", "");
                    hashMap.put("page", (String) fields.get("pageName"));
                    hashMap.put("signature", (String) fields.get("signature"));
                    hashMap.put("rightType", (String) fields.get("rightType"));
                    hashMap.put("cachable", (String) fields.get("cachable"));
                    hash = executeUpload(request, context, in, fileName, fileSize, hashMap, response);
                }
                newName = fileName;
            } catch (Exception ex) {
                log.debug("Error on upload picture", ex);
                request.setAttribute(RETVAL, "203");
                request.setAttribute(ERRORMESSAGE, rb.getString("uploader.parsepara"));
            }
        } else {
            request.setAttribute(RETVAL, "1");
            request.setAttribute(ERRORMESSAGE, rb.getString("uploader.invalidxml"));
        }
    }

    printScript(request, response, newName, hash);

    log.debug("--- END DOPOST ---");
}

From source file:it.eng.spagobi.engines.worksheet.services.designer.UploadWorksheetImageAction.java

public void service(SourceBean request, SourceBean response) {

    logger.debug("IN");

    try {//from   w  w  w  .ja  v  a  2s  .c o m
        super.service(request, response);

        FileItem uploaded = (FileItem) request.getAttribute("UPLOADED_FILE");
        if (uploaded == null) {
            throw new SpagoBIEngineServiceException(getActionName(), "No file was uploaded");
        }

        UserProfile userProfile = (UserProfile) getEnv().get(EngineConstants.ENV_USER_PROFILE);
        logger.info("User [id : " + userProfile.getUserId() + ", name : " + userProfile.getUserName() + "] "
                + "is uploading file [" + uploaded.getName() + "] with size [" + uploaded.getSize() + "]");

        checkUploadedFile(uploaded);

        logger.debug("Saving file...");
        saveFile(uploaded);
        logger.debug("File saved");

        replayToClient(null);

    } catch (Throwable t) {
        SpagoBIEngineServiceException e = SpagoBIEngineServiceExceptionHandler.getInstance()
                .getWrappedException(getActionName(), getEngineInstance(), t);
        replayToClient(e);
    } finally {
        logger.debug("OUT");
    }

}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

public Hashtable getHashtable(HttpServletRequest request) throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {//from  w w w  .j av  a  2s .c o  m
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}

From source file:com.silverpeas.form.displayers.AbstractFileFieldDisplayer.java

protected String processUploadedFile(List<FileItem> items, String parameterName, PagesContext pagesContext)
        throws IOException {
    String attachmentId = null;//from w  ww  . j  av a  2 s.c  om
    FileItem item = FileUploadUtil.getFile(items, parameterName);
    if (item != null && !item.isFormField()) {
        String componentId = pagesContext.getComponentId();
        String userId = pagesContext.getUserId();
        String objectId = pagesContext.getObjectId();
        if (StringUtil.isDefined(item.getName())) {
            String fileName = FileUtil.getFilename(item.getName());
            long size = item.getSize();
            if (size > 0L) {
                SimpleDocument document = createSimpleDocument(objectId, componentId, item, fileName, userId,
                        false);
                attachmentId = document.getId();
            }
        }
    }
    return attachmentId;
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

private String[] processUploadedFile(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor)
        throws ZipException, IOException, SpagoBIEngineException {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    if (fieldName.equalsIgnoreCase("deploymentDescriptor"))
        return null;

    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    File jobsDir = new File(runtimeRepository.getRootDir(),
            jobDeploymentDescriptor.getLanguage().toLowerCase());
    File projectDir = new File(jobsDir, jobDeploymentDescriptor.getProject());
    File tmpDir = new File(projectDir, "tmp");
    if (!tmpDir.exists())
        tmpDir.mkdirs();//  w w w  .  j  ava 2 s.com
    File uploadedFile = new File(tmpDir, fileName);

    try {
        item.write(uploadedFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String[] dirNames = ZipUtils.getDirectoryNameByLevel(new ZipFile(uploadedFile), 2);
    List dirNameList = new ArrayList();
    for (int i = 0; i < dirNames.length; i++) {
        if (!dirNames[i].equalsIgnoreCase("lib"))
            dirNameList.add(dirNames[i]);
    }
    String[] jobNames = (String[]) dirNameList.toArray(new String[0]);

    runtimeRepository.deployJob(jobDeploymentDescriptor, new ZipFile(uploadedFile));
    uploadedFile.delete();
    tmpDir.delete();

    return jobNames;
}

From source file:eionet.gdem.utils.MultipartFileUpload.java

/**
 * Returns file as InputStream// w  w w.  j  a v  a2  s. co m
 * @param fieldName Field name
 * @return InputStream
 * @throws GDEMException If an error occurs.
 * @throws IOException If an error occurs.
 */
public InputStream getFileAsInputStream(String fieldName) throws GDEMException, IOException {

    FileItem fileItem = getFileItem(fieldName);
    if (fileItem == null)
        throw new GDEMException("No files found!");

    if (fileItem.getSize() == 0)
        throw new GDEMException("File size is 0KB!"); // There is nothing to save, file size is 0

    return fileItem.getInputStream();
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

protected Map parseUploadParameter(String name, FileItem item, Map uploads) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Upload param-name: " + name);
        LOGGER.debug("Upload item size: " + item.getSize() + " bytes");
    }//from ww w  .  j  a v a  2s . c o  m
    if (uploads == null) {
        uploads = new HashMap();
    }

    String id = name.substring(getDataPrefix().length());
    uploads.put(id, item);
    return uploads;
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

private void publishOnSpagoBI(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor)
        throws ZipException, IOException, SpagoBIEngineException {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    if (fieldName.equalsIgnoreCase("deploymentDescriptor"))
        return;//from ww  w .  ja  va2s .  c  o m

    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();

    String projectName = jobDeploymentDescriptor.getProject();
    String projectLanguage = jobDeploymentDescriptor.getLanguage().toLowerCase();
    String jobName = "JOB_NAME";
    String contextName = "Default";
    String template = "";
    template += "<etl>\n";
    template += "\t<job project=\"" + projectName + "\" ";
    template += "jobName=\"" + projectName + "\" ";
    template += "context=\"" + projectName + "\" ";
    template += "language=\"" + contextName + "\" />\n";
    template += "</etl>";

    BASE64Encoder encoder = new BASE64Encoder();
    String templateBase64Coded = encoder.encode(template.getBytes());

    TalendEngineConfig config = TalendEngineConfig.getInstance();

    String user = "biadmin";
    String password = "biadmin";
    String label = "ETL_JOB";
    String name = "EtlJob";
    String description = "Etl Job";
    boolean encrypt = false;
    boolean visible = true;
    String functionalitiyCode = config.getSpagobiTargetFunctionalityLabel();
    String type = "ETL";
    String state = "DEV";

    try {

        //PublishAccessUtils.publish(spagobiurl, user, password, label, name, description, encrypt, visible, type, state, functionalitiyCode, templateBase64Coded);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:au.edu.unimelb.news.servlet.ImportServlet.java

/**
 * Reads all user input related to creating a new agenda item and creates the agenda item.
 *//*from w  ww  .  ja v  a 2  s. c  o m*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    User user = UserHelper.getUser(request);
    response.setContentType("text/html");
    PrintWriter out = new PrintWriter(response.getOutputStream());
    LayoutHelper.headerTitled(out, "Import");
    LayoutHelper.menubar(out, user);

    out.println("<div id=\"breadcrumbs\">");
    out.println("<a href=\"http://www.unimelb.edu.au\">University home</a> &gt;");
    out.println("<a href=\"" + Configuration.appPrefix + "/\">University News</a> &gt;");
    out.println("Document Import");
    out.println("</div>");

    out.println("<div id=\"content\">");
    out.println("<h2>Importing</h2>");

    //out.flush();

    /*
     *  This chunk calls the Jakarta Commons Fileupload component to
     *  process the file upload information.
     */
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    /*
     * Use the Jakarta Commons Fileupload component to read the
     * field variables.
     */
    try {
        out.println("<ul>");
        String filename = "";
        for (FileItem field : items) {
            if (!field.isFormField()) {
                filename = field.getName();
                if (filename.contains("/"))
                    filename = filename.substring(filename.lastIndexOf('/') + 1);
                if (filename.contains("\\"))
                    filename = filename.substring(filename.lastIndexOf('\\') + 1);
                int no = random.nextInt();
                if (no < 1)
                    no = -no;
                if (filename.length() > 0 && field.getSize() > 0
                        && field.getFieldName().equals("import_file")) {
                    ArticleImport helper = new ArticleImport(new ArticleImportResponder(user, out));
                    helper.process(field.getInputStream(), user);
                }
            }
        }
        out.println("</ul>");
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    out.println("File upload processing complete.");

    out.println("</div>");
    LayoutHelper.footer(out);

    out.flush();
    out.close();
}