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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:fi.vm.sade.organisaatio.resource.TempFileResource.java

@POST
@Path("/")
@Produces(MediaType.TEXT_PLAIN)/*from  www.ja va  2s .com*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Secured({ "ROLE_APP_ORGANISAATIOHALLINTA" })
public String addImage(@Context HttpServletRequest request, @Context HttpServletResponse response) {
    LOG.info("Adding attachment " + request.getMethod());
    Map<String, String> result = null;

    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            for (FileItem item : upload.parseRequest(request)) {
                if (item.getName() != null) {
                    result = storeAttachment(item);
                }
            }
        } else {
            response.setStatus(400);
            response.getWriter().append("Not a multipart request");
        }
        LOG.info("Added attachment: " + result);
        JSONObject json = new JSONObject(result);
        return json.toString();
    } catch (Exception e) {
        return "organisaatio.fileupload.error";
    }
}

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 {//from ww w .  ja v a 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:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;//  w w  w.j av a 2s  .c  o  m
    Integer serial = 0;
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Delete an uploaded file./*from   ww w.  j a va  2 s  .  co  m*/
 * 
 * @param request
 * @param response
 * @return FileItem
 * @throws IOException
 */
protected static FileItem removeUploadedFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_REMOVE);

    FileItem item = findFileItem(getSessionFileItems(request), parameter);
    if (item != null) {
        getSessionFileItems(request).remove(item);
        renderXmlResponse(request, response, XML_DELETED_TRUE);
        logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter
                + " " + item.getName() + " " + item.getSize());
    } else {
        renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
        logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter
                + " unable to delete file because it isn't in session.");
    }

    return item;
}

From source file:Controller.UpLoadFile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if its multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> multiparts = upload.parseRequest(request);

        for (FileItem item : multiparts) {
            if (!item.isFormField()) {
                String name = new File(item.getName()).getName();
                item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
            }/*from   w  w  w .j  a  v  a 2s.  com*/
        }
    }
    RequestDispatcher rd = request.getRequestDispatcher("loadimage.jsp");
    rd.forward(request, response);
}

From source file:hudson.plugins.sidebar_link.SidebarLinkPlugin.java

/**
 * Receive file upload from startUpload.jelly.
 * File is placed in $JENKINS_HOME/userContent directory.
 *//*w w  w .j  a  va2 s . c  o  m*/
public void doUpload(StaplerRequest req, StaplerResponse rsp)
        throws IOException, ServletException, InterruptedException {
    Hudson hudson = Hudson.getInstance();
    hudson.checkPermission(Hudson.ADMINISTER);
    FileItem file = req.getFileItem("linkimage.file");
    String error = null, filename = null;
    if (file == null || file.getName().isEmpty())
        error = Messages.NoFile();
    else {
        filename = "userContent/"
                // Sanitize given filename:
                + file.getName().replaceFirst(".*/", "").replaceAll("[^\\w.,;:()#@!=+-]", "_");
        FilePath imageFile = hudson.getRootPath().child(filename);
        if (imageFile.exists())
            error = Messages.DupName();
        else {
            imageFile.copyFrom(file.getInputStream());
            imageFile.chmod(0644);
        }
    }
    rsp.setContentType("text/html");
    rsp.getWriter().println((error != null ? error : Messages.Uploaded("<tt>/" + filename + "</tt>"))
            + " <a href=\"javascript:history.back()\">" + Messages.Back() + "</a>");
}

From source file:com.alibaba.sample.petstore.biz.StoreManagerTests.java

@Test
public void addProduct() throws Exception {
    Product prod = new Product();
    final File srcfile = new File(srcdir, "resources.xml");

    prod.setProductId("myfish");
    prod.setDescription("My fish");
    prod.setName("my fish");

    FileItem fi = createMock(FileItem.class);
    expect(fi.getName()).andReturn("c:\\test\\pic.gif");
    expect(fi.getInputStream()).andAnswer(new IAnswer<InputStream>() {
        public InputStream answer() throws Throwable {
            return new FileInputStream(srcfile);
        }// ww w  .ja v a  2  s . co m
    });
    replay(fi);

    storeManager.addProduct(prod, "FISH", fi);

    prod = productDao.getProductById("myfish");
    assertEquals("myfish", prod.getProductId());
    assertEquals("my fish", prod.getName());
    assertEquals("My fish", prod.getDescription());
    assertEquals("FISH", prod.getCategoryId());
    assertTrue(prod.getLogo().startsWith("image_"));
    assertTrue(prod.getLogo().endsWith(".gif"));

    File f = new File(destdir, "upload/" + prod.getLogo());
    assertTrue(f.exists());

    assertEquals(StreamUtil.readText(new FileInputStream(srcfile), "8859_1", true),
            StreamUtil.readText(new FileInputStream(f), "8859_1", true));
}

From source file:hu.ptemik.gallery.servlets.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    User user = (User) session.getAttribute("user");
    String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    if (ServletFileUpload.isMultipartContent(request) && user != null) {
        try {// w  w w. ja v  a 2  s . c o  m
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Picture pic = new Picture();
            File uploadedFile = null;

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    String relativePath = UPLOAD_DIRECTORY + "/" + fileName;

                    uploadedFile = new File(filePath);
                    item.write(uploadedFile);

                    pic.setUrl(relativePath);
                } else {
                    if (item.getFieldName().equals("title")) {
                        pic.setTitle(item.getString());
                    } else if (item.getFieldName().equals("description")) {
                        pic.setDescription(item.getString());
                    }
                }
            }

            if (Controller.newPicture(pic, user)) {
                request.setAttribute("successMessage", "A fjl feltltse sikerlt!");
            } else {
                FileUtils.deleteQuietly(uploadedFile);
                throw new Exception();
            }
        } catch (FileNotFoundException ex) {
            request.setAttribute("errorMessage", "Hinyzik a fjl!");
        } catch (Exception ex) {
            request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!");
        }
    } else {
        request.setAttribute("errorMessage", "Form hiba");
    }

    request.getRequestDispatcher("upload.jsp").forward(request, response);
}

From source file:controller.uploadTeste.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* www . ja  v  a  2 s .  c  om*/
 *
 * @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 {

    String idLocal = (String) request.getParameter("idLocal");

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/novoLocalTeste.jsp?nomeArquivo=" + name).forward(request, response);

}

From source file:Control.HandleTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww . j av  a  2  s  . 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 {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();

        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        String name;
        if (ServletFileUpload.isMultipartContent(request)) {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    // temp.logoImage = Paths.logoPath + name;
                    String FilePath = path + Paths.logoPathStore + name;
                    item.write(new File(FilePath));
                }
            }
        }
    } catch (Exception e) {

    }
}