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:com.silverpeas.thumbnail.servlets.ThumbnailRequestRouter.java

private ThumbnailDetail saveFile(List<FileItem> parameters) throws Exception {
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_ENTER_METHOD");

    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean runOnUnix = settings.getBoolean("runOnSolaris", false);

    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "runOnUnix = " + runOnUnix);

    String componentId = FileUploadUtil.getParameter(parameters, "ComponentId");
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "componentId = " + componentId);
    String id = FileUploadUtil.getParameter(parameters, "ObjectId");
    SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
            "id = " + id);

    FileItem item = FileUploadUtil.getFile(parameters, "OriginalFile");

    String fullFileName;//from   w  w  w  .j  a  va  2s  .co  m
    if (!item.isFormField()) {

        fullFileName = item.getName();
        if (fullFileName != null && runOnUnix) {
            fullFileName = fullFileName.replace('\\', File.separatorChar);
            SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                    "fullFileName on Unix = " + fullFileName);
        }

        assert fullFileName != null;
        String fileName = fullFileName.substring(fullFileName.lastIndexOf(File.separator) + 1,
                fullFileName.length());
        SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                "file = " + fileName);

        long size = item.getSize();
        SilverTrace.info("thumbnail", "ThumbnailRequestRouter.createAttachment", "root.MSG_GEN_PARAM_VALUE",
                "size = " + size);

        String type = null;
        if (fileName.lastIndexOf(".") != -1) {
            type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        }

        if (type == null || type.length() == 0) {
            throw new ThumbnailRuntimeException("ThumbnailRequestRouter.saveFile()",
                    SilverpeasRuntimeException.ERROR, "thumbnail_MSG_TYPE_KO");
        }

        String physicalName = System.currentTimeMillis() + "." + type;

        String filePath = FileRepositoryManager.getAbsolutePath(componentId)
                + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName;
        File file = new File(filePath);

        if (!file.exists()) {
            FileFolderManager.createFolder(file.getParentFile());
            file.createNewFile();
        }

        item.write(file);
        String mimeType = FileUtil.getMimeType(fileName);

        String objectType = FileUploadUtil.getParameter(parameters, "ObjectType");
        ThumbnailDetail thumbToAdd = new ThumbnailDetail(componentId, Integer.valueOf(id),
                Integer.valueOf(objectType));
        thumbToAdd.setOriginalFileName(physicalName);
        thumbToAdd.setMimeType(mimeType);

        return thumbToAdd;
    }
    return null;
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 * @param item/*from  w  w w  . j  av  a  2  s .  c o m*/
 * @return the file handle
 */
private File processUploadedFile(FileItem item) {
    // A random folder in the system temporary directory and write the file there
    String folder = System.getProperty("java.io.tmpdir") + File.separator
            + RandomStringUtils.randomAlphabetic(5);
    File file = null;

    try {
        FileUtils.forceMkdir(new File(folder));
        file = new File(folder + File.separator + item.getName());
        item.write(file);

    } catch (IOException e) {
        logger.error("IOException while processUploadedFile: " + item.getName());
        logger.error(e);

    } catch (Exception e) {
        logger.error("Exception while processUploadedFile: " + item.getName());
        logger.error(e);
    }

    return file;
}

From source file:hudson.PluginManager.java

/**
 * Uploads a plugin./*www  .  j  a  v  a2s .c  o  m*/
 */
public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException {
    try {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
        String fileName = Util.getFileName(fileItem.getName());
        if (!fileName.endsWith(".hpi"))
            throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName));
        fileItem.write(new File(rootDir, fileName));
        fileItem.delete();

        pluginUploaded = true;

        return new HttpRedirect(".");
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {// grrr. fileItem.write throws this
        throw new ServletException(e);
    }
}

From source file:hd.controller.AddImageToIdeaBookServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w.  ja va 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 {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);

                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;

                        File savedFile = new File(RealPath);
                        item.write(savedFile);

                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);

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

                }
            }

            String ideaBookIdTemp = (String) params.get("txtIdeabookId");
            int ideaBookId = Integer.parseInt(ideaBookIdTemp);
            IdeaBookDAO ideabookDao = new IdeaBookDAO();

            String tilte = (String) params.get("newGalleryName");

            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;

            IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO();
            IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId);

            HDSystem system = new HDSystem();
            system.setNotificationIdeaBook(request);
            response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId);

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:ilarkesto.form.UploadFormField.java

@Override
public void update(Map<String, String> data, Collection<FileItem> uploadedFiles) {
    maxFileSizeExceeded = false;//w  ww  .  j  a  v  a  2 s.c om
    for (FileItem item : uploadedFiles) {
        if (item.getFieldName().equals(getName())) {
            if (item.getSize() == 0) {
                file = null;
                return;
            }
            if (maxFilesize != null && item.getSize() > maxFilesize) {
                maxFileSizeExceeded = true;
                return;
            }
            file = new File(applicationTempDir + "/" + folderIdGenerator.generateId() + "/" + item.getName());
            file.getParentFile().mkdirs();
            try {
                item.write(file);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:com.vaporwarecorp.mirror.component.configuration.WebServer.java

private File getFile(FileItem fileItem) {
    Storage storage;//from   w ww .  ja va2 s .  c o  m
    if (SimpleStorage.isExternalStorageWritable()) {
        storage = SimpleStorage.getExternalStorage();
    } else {
        storage = SimpleStorage.getInternalStorage(mAppManager.getAppContext());
    }
    storage.createDirectory("configuration/uploads");
    storage.createFile("configuration/uploads", fileItem.getName(), new byte[0]);
    return storage.getFile("configuration/uploads", fileItem.getName());
}

From source file:net.morphbank.mbsvc3.webservices.Uploader.java

private String saveTempFile(FileItem item) {
    FileOutputStream outputStream;
    String filename = "";

    if (item.getName().endsWith(".xls")) {
        filename = folderPath + "temp.xls";
    } else {/*ww w. jav  a2s . c o  m*/
        filename = folderPath + "temp.csv";
    }
    try {
        outputStream = new FileOutputStream(filename);
        outputStream.write(item.get());
        outputStream.close();
        return folderPath;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.stratelia.webactiv.agenda.servlets.AgendaRequestRouter.java

private File processFormUpload(AgendaSessionController agendaSc, HttpServletRequest request) {
    String logicalName = "";
    String tempFolderName = "";
    String tempFolderPath = "";
    String fileType = "";
    long fileSize = 0;
    File fileUploaded = null;/*www. ja  v a2s. c om*/
    try {
        List<FileItem> items = HttpRequest.decorate(request).getFileItems();
        FileItem fileItem = FileUploadUtil.getFile(items, "fileCalendar");
        if (fileItem != null) {
            logicalName = fileItem.getName();
            if (logicalName != null) {
                logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1,
                        logicalName.length());

                // Name of temp folder: timestamp and userId
                tempFolderName = new Long(new Date().getTime()).toString() + "_" + agendaSc.getUserId();

                // Mime type of the file
                fileType = fileItem.getContentType();
                fileSize = fileItem.getSize();

                // Directory Temp for the uploaded file
                tempFolderPath = FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                        + tempFolderName;
                if (!new File(tempFolderPath).exists()) {
                    FileRepositoryManager.createAbsolutePath(agendaSc.getComponentId(),
                            GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                                    + tempFolderName);
                }

                // Creation of the file in the temp folder
                fileUploaded = new File(FileRepositoryManager.getAbsolutePath(agendaSc.getComponentId())
                        + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator
                        + tempFolderName + File.separator + logicalName);
                fileItem.write(fileUploaded);

                // Is a real file ?
                if (fileSize > 0) {
                    SilverTrace.debug("agenda", "AgendaRequestRouter.processFormUpload()",
                            "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize="
                                    + fileSize + " fileType=" + fileType);
                }
            }
        }
    } catch (Exception e) {
        // Other exception
        SilverTrace.warn("agenda", "AgendaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED",
                e);
    }
    return fileUploaded;
}

From source file:com.alibaba.citrus.service.requestcontext.parser.ParserRequestContextTests.java

@Test
public void multipartForm() throws Exception {
    assertEquals("hello", requestContext.getParameters().getString("myparam"));

    // ??file item
    FileItem fileItem = requestContext.getParameters().getFileItem("myfile");

    assertEquals("myfile", fileItem.getFieldName());
    assertEquals(new File(srcdir, "smallfile.txt"), new File(fileItem.getName()));
    assertFalse(fileItem.isFormField());
    assertEquals(new String("?".getBytes("GBK"), "8859_1"), fileItem.getString());
    assertEquals("?", fileItem.getString("GBK"));
    assertTrue(fileItem.isInMemory());/*from www.  ja  v  a  2  s.  c  om*/

    // ?file items
    FileItem[] fileItems = requestContext.getParameters().getFileItems("myfile");
    String[] fileNames = requestContext.getParameters().getStrings("myfile");

    assertEquals(fileItems.length, fileNames.length);
    assertEquals(4, fileNames.length);

    assertEquals(new File(srcdir, "smallfile.txt"), new File(fileItems[0].getName()));
    assertEquals(new File(srcdir, "smallfile_.JPG"), new File(fileItems[1].getName())); // case insensitive
    assertEquals(new File(srcdir, "smallfile.gif"), new File(fileItems[2].getName()));
    assertEquals(new File(srcdir, "smallfile"), new File(fileItems[3].getName()));

    assertEquals(new File(srcdir, "smallfile.txt"), new File(fileNames[0]));
    assertEquals(new File(srcdir, "smallfile_.JPG"), new File(fileNames[1])); // case insensitive
    assertEquals(new File(srcdir, "smallfile.gif"), new File(fileNames[2]));
    assertEquals(new File(srcdir, "smallfile"), new File(fileNames[3]));

    // request??
    assertEquals("hello", newRequest.getParameter("myparam"));
    assertEquals(new File(srcdir, "smallfile.txt"), new File(newRequest.getParameter("myfile")));
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

@RequestMapping(value = "EenviarMailA.htm", method = RequestMethod.POST)
public String enviarMailA_post(@ModelAttribute("correo") correoNoLeidos c, BindingResult result,
        HttpServletRequest request) {//w ww. jav a 2  s  . c o m
    String mensaje = "";

    try {
        //MultipartFile multipart = c.getArchivo();
        System.out.println("olaEnviarMAILS");
        String ubicacionArchivo = "C:\\DecorakiaReportesIntranet\\archivosMail\\";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            arc.add(item.getName());
            System.out.println("img" + item.getName());
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:EenviarMail.htm";

}