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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:com.king.platform.net.http.integration.MultiPart.java

@Test
public void postMultiPart() throws Exception {

    AtomicReference<List<FileItem>> partReferences = new AtomicReference<>();
    AtomicReference<Exception> exceptionReference = new AtomicReference<>();

    integrationServer.addServlet(new HttpServlet() {
        @Override//from   www.java2  s.  c om
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                partReferences.set(fileItems);
            } catch (FileUploadException e) {
                exceptionReference.set(e);
            }

        }
    }, "/testMultiPart");

    httpClient
            .createPost(
                    "http://localhost:" + port + "/testMultiPart")
            .idleTimeoutMillis(
                    0)
            .totalRequestTimeoutMillis(
                    0)
            .content(
                    new MultiPartBuilder()
                            .addPart(
                                    MultiPartBuilder
                                            .create("text1", "Message 1",
                                                    StandardCharsets.ISO_8859_1)
                                            .contentType("multipart/form-data"))
                            .addPart(MultiPartBuilder.create("binary1", new byte[] { 0x00, 0x01, 0x02 })
                                    .contentType("application/octet-stream").charset(StandardCharsets.UTF_8)
                                    .fileName("application.bin"))
                            .addPart(MultiPartBuilder.create("text2", "Message 2", StandardCharsets.ISO_8859_1))
                            .build())
            .build().execute().join();

    assertNull(exceptionReference.get());

    List<FileItem> fileItems = partReferences.get();
    FileItem fileItem = fileItems.get(1);
    assertEquals("application/octet-stream; charset=UTF-8", fileItem.getContentType());
    assertEquals("binary1", fileItem.getFieldName());
    assertEquals("application.bin", fileItem.getName());

}

From source file:id.go.customs.training.gudang.web.BarangUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Boolean adaFile = ServletFileUpload.isMultipartContent(req);
    if (adaFile) {
        try {/* w  w w .  j ava 2  s . c o m*/
            String lokasiLengkap = req.getServletContext().getRealPath(lokasiPenyimpanan);
            System.out.println("Lokasi hasil upload : " + lokasiLengkap);

            // inisialisasi prosesor upload
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File lokasiSementaraHasilUpload = (File) req.getServletContext()
                    .getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(lokasiSementaraHasilUpload);
            System.out.println("Lokasi upload sementara : " + lokasiSementaraHasilUpload.getAbsolutePath());
            ServletFileUpload prosesorUpload = new ServletFileUpload(factory);

            List<FileItem> hasilUpload = prosesorUpload.parseRequest(req);
            System.out.println("Jumlah file = " + hasilUpload.size());

            for (FileItem fileItem : hasilUpload) {
                System.out.println("----- Informasi File -----");
                System.out.println("Tipe File : " + fileItem.getContentType());
                System.out.println("Nama Field : " + fileItem.getFieldName());
                System.out.println("Nama File : " + fileItem.getName());
                System.out.println("Ukuran File : " + fileItem.getSize());

                String fileTujuan = lokasiLengkap + File.separator + fileItem.getName();
                File tujuan = new File(fileTujuan);
                fileItem.write(tujuan);
                System.out.println("Hasil upload ada di " + fileTujuan);

                HasilImportBarang hasil = BarangImporter.importCsv(tujuan);
                req.setAttribute("hasil", hasil);
            }
        } catch (Exception ex) {
            Logger.getLogger(BarangUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // selesai upload, tampilkan hasil upload
    req.getRequestDispatcher("/WEB-INF/templates/jsp/barang/import.jsp").forward(req, resp);
}

From source file:com.sa.osgi.jetty.UploadServlet.java

private void processUploadedFile(FileItem item) {
    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();

    System.out.println("file name: " + fileName);
    try {// www. ja  va 2s.  co  m
        //            InputStream inputStream = item.getInputStream();
        //            FileOutputStream fout = new FileOutputStream("/tmp/aa");
        //            fout.write(inputStream.rea);
        String newFileName = "/tmp/" + fileName;
        item.write(new File(newFileName));
        ServiceFactory factory = ServiceFactory.INSTANCE;
        MaoService maoService = factory.getMaoService();
        boolean b = maoService.installBundle(newFileName);
        System.out.println("Installation Result: " + b);

    } catch (IOException ex) {
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.mylop.servlet.ImageServlet.java

public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    HttpSession session = request.getSession();
    String account = (String) session.getAttribute("userid");
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {/*from w w  w.  j av a2  s  . c o  m*/
            List<FileItem> multiparts = upload.parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    String[] ext = contentType.split("/");

                    String fileName = UPLOAD_DIRECTORY + File.separator + account + "_Avatar";
                    File file = new File(fileName);

                    item.write(file);
                    String avatarUrl = "http://mylop.tk:8080/Avatar/" + account + "_Avatar";
                    ProfileModel pm = new ProfileModel();
                    Map<String, String> update = new HashMap<String, String>();
                    update.put("avatar", avatarUrl);
                    pm.updateProfile(account, update);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String json = "{\"message\": \"success\"}";
    response.getWriter().write(json);

}

From source file:br.gov.jfrj.siga.wf.servlet.UploadServlet.java

/**
 * Verifica se o arquivo enviado  um process definition. Se for, realiza o
 * seu deploy.//from   www .  j  a v  a 2 s  .co m
 * 
 * @param request
 * @return
 */
private String handleRequest(HttpServletRequest request) {
    if (!FileUpload.isMultipartContent(request)) {
        log.debug("Not a multipart request");
        return "Not a multipart request";
    }
    try {
        // Nato: Modo novo, mas que esta voltando uma lista vazia pois o
        // webwork est interceptando o request e lendo o arquivo
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Configure the uploader here, if desired.
        List list = upload.parseRequest(request);

        // Nato: modo antigo
        // DiskFileUpload fileUpload = new DiskFileUpload();
        // List list = fileUpload.parseRequest(request);

        // MultiPartRequestWrapper req = (MultiPartRequestWrapper)request;
        // req.get

        Iterator iterator = list.iterator();
        if (!iterator.hasNext()) {
            log.debug("No process file in the request");
            return "No process file in the request";
        }
        FileItem fileItem = (FileItem) iterator.next();
        if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
            log.debug("Not a process archive");
            return "Not a process archive";
        }
        return doDeployment(fileItem);
    } catch (FileUploadException e) {
        e.printStackTrace();
        return "FileUploadException";
    } catch (Exception e) {
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:hudson.jbpm.PluginImpl.java

/**
 * Method supporting upload from the designer at /plugin/jbpm/upload
 *///from  w ww .  ja  v  a 2 s . co m
public void doUpload(StaplerRequest req, StaplerResponse rsp)
        throws FileUploadException, IOException, ServletException {
    try {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);

        if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
            throw new IOException("Not a process archive");
        }

        log.fine("Deploying process archive " + fileItem.getName());
        ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream());
        JbpmContext jbpmContext = getCurrentJbpmContext();
        log.fine("Preparing to parse process archive");
        ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
        log.fine("Created a processdefinition : " + processDefinition.getName());
        jbpmContext.deployProcessDefinition(processDefinition);
        zipInputStream.close();
        rsp.forwardToPreviousPage(req);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Add the <code>FileItem</code> as a document into the <code>MultipartForm</code>.
 *//*from   www. j  a v  a  2  s.  com*/
private void addFile(FileItem item, MultipartForm form) throws Exception {
    String atomName = item.getFieldName();
    String fileName = item.getName();
    String type = item.getContentType();
    File file = File.createTempFile(atomName, null, this.tempDir);
    item.write(file);

    form.addDocument(atomName, fileName, type, file);
}

From source file:ccc.plugins.multipart.apache.MultipartForm.java

/** {@inheritDoc} */
@Override/*from w w  w .  j a  v  a2  s .c  o m*/
public String getContentType(final String string) {
    final FileItem item = getFormItem(string);
    return (null == item) ? null : item.getContentType();
}

From source file:emsa.webcoc.cleanup.servlet.UploadServet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  w.  j  a v a2s. co  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 {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>XML file clean up</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 into memory
    factory.setSizeThreshold(MAXMEMSIZE);
    //Path to save file if its size is bigger than MAXMEMSIZE
    factory.setRepository(new File(REPOSITORY));
    ServletFileUpload upload = new ServletFileUpload(factory);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>XML file clean up</title>");
    out.println("</head>");
    out.println("<body>");

    try {
        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> t = fileItems.iterator();

        while (t.hasNext()) {
            FileItem f = t.next();

            if (!f.isFormField()) {
                if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file

                    String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name
                    String location = (String) this.getServletContext().getAttribute("newFileLocation");

                    CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location);

                    if (clean.cleanDocument(f.getInputStream()) == 0) {
                        out.println("<h3>" + f.getName() + " was clean</h3>");
                        out.println(clean.printHTMLStatistics());
                        out.println("<br /><form action='download?filename=" + uniqueFileName
                                + "' method='post'><input type='submit' value='Download'/></form></body></html>");
                    } else {
                        out.println("<h3>" + clean.getErrorMessage() + "</h3>");
                        out.println(
                                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    }
                } else {
                    out.println("<h3>The file " + f.getName() + " is not an xml file</h3>");
                    out.println(
                            "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType());
                }
            }
        }

        File repository = factory.getRepository();
        cleanTmpFiles(repository);

    } catch (IOException | FileUploadException e) {
        out.println("<h3>Something went wrong</h3></br>");
        out.println(
                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
    }
}

From source file:com.exedio.cope.live.MediaServlet.java

void doRequest(final HttpServletRequest request, final HttpServletResponse response, final Anchor anchor) {
    final String featureID = request.getParameter(FEATURE);
    if (featureID == null)
        throw new NullPointerException();
    final Media feature = (Media) model.getFeature(featureID);
    if (feature == null)
        throw new NullPointerException(featureID);

    final String itemID = request.getParameter(ITEM);
    if (itemID == null)
        throw new NullPointerException();

    final Item item;
    try {/*from w w w  . j  a  v  a  2  s . c o m*/
        startTransaction("media(" + featureID + ',' + itemID + ')');
        item = model.getItem(itemID);
        model.commit();
    } catch (final NoSuchIDException e) {
        throw new RuntimeException(e);
    } finally {
        model.rollbackIfNotCommitted();
    }

    final FileItem fi = anchor.getModification(feature, item);
    if (fi == null)
        throw new NullPointerException(featureID + '-' + itemID);
    response.setContentType(fi.getContentType());
    response.setContentLength((int) fi.getSize());

    InputStream in = null;
    ServletOutputStream out = null;
    try {
        in = fi.getInputStream();
        out = response.getOutputStream();

        final byte[] b = new byte[20 * 1024];
        for (int len = in.read(b); len >= 0; len = in.read(b))
            out.write(b, 0, len);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}