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.naval.persistencia.hibernate.SubirArchivo.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w ww  . j a v  a 2  s.c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String idSolicitud = request.getParameter("idSolicitud");
    String accion = request.getParameter("accion");
    if (accion != null && "editarSolicitud".equals(accion)) {
        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
        PrintWriter writer = response.getWriter();

        List<FileItem> items;
        try {
            items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {

                    FileItem actual = null;
                    actual = item;
                    String fileName = actual.getName();

                    String str = request.getSession().getServletContext().getRealPath("/adjuntos/");
                    fileName = idSolicitud + "-" + fileName;
                    // nos quedamos solo con el nombre y descartamos el path
                    File fichero = new File(str + "\\" + fileName);

                    try {
                        actual.write(fichero);
                        String aux = "{" + "\"name\":\"" + fichero.getName() + "\",\"size\":\"" + 2000
                                + "\",\"url\":\"/adjuntos/" + fichero.getName()
                                + "\",\"thumbnailUrl\":\"/thumbnails/" + fichero.getName()
                                + "\",\"deleteUrl\":\"/Subir?file=" + fichero.getName()
                                + "\",\"deleteType\":\"DELETE" + "\",\"type\":\"" + fichero.getName() + "\"}";

                        writer.write("{\"files\":[" + aux + "]}");
                    } catch (Exception e) {
                    }
                }
            }
        } catch (Exception ex) {
        }

    } else {
        processRequest(request, response);
    }

}

From source file:by.iharkaratkou.TestServlet.java

public String processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filenameTimestamp = "";

    try {/*from ww w .  ja v  a  2s  . c  o m*/
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (!ismultipart) {
            System.out.println("ismultipart is false");
        } else {
            System.out.println("ismultipart is true");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {

                items = upload.parseRequest(request);
            } catch (Exception e) {
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {

                } else {
                    String itemname = item.getName();
                    if ((itemname == null || itemname.equals(""))) {
                        continue;
                    }
                    String filename = FilenameUtils.getName(itemname);
                    System.out.println(filename);
                    File f = checkExist(filename);
                    item.write(f);
                    if (f.getName().contains(".xlsx")) {
                        filenameTimestamp = f.getName();
                    }
                }
            }
        }

    } catch (Exception e) {

    } finally {
        out.close();
    }
    return filenameTimestamp;
}

From source file:com.app.framework.web.MultipartFilter.java

/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 *
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 *//* ww  w .j  a  v a2s .c o  m*/
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @throws IOException//from  w  ww  .  j a  v a2s . com
 * @throws ServletException
 */
@UrlPattern("/upload/test1.html")
public void test1() throws IOException, ServletException {
    logger.info("method: " + this.request.getMethod() + " " + this.request.getRequestURI() + " "
            + this.request.getQueryString());
    String home = this.servletContext.getRealPath("/WEB-INF/tmp");
    Map<String, Object> result = new HashMap<String, Object>();
    RandomAccessFile raf = null;

    try {
        Map<String, Object> map = this.parse(this.request);
        FileItem fileItem = (FileItem) map.get("fileData");
        fileItem.write(new File(home, fileItem.getName()));
        result.put("status", 200);
        result.put("message", "??");
        result.put("start", fileItem.getSize());
        JsonUtil.callback(this.request, this.response, result);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.put("status", 500);
        result.put("message", "?");
        JsonUtil.callback(this.request, this.response, result);
        return;
    } finally {
        close(raf);
    }
}

From source file:dk.dma.msinm.legacy.nm.LegacyNmImportRestService.java

/**
 * Imports an uploaded NtM PDF file//from ww w  .  ja  v  a  2s .c  om
 *
 * @param request the servlet request
 * @return a status
 */
@POST
@Path("/upload-pdf")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public String importPDF(@Context HttpServletRequest request) throws Exception {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            // NM PDF
            if (NmPdfExtractor.getFileNameMatcher(item.getName()).matches()) {
                StringBuilder txt = new StringBuilder();
                importNmPdf(item.getInputStream(), item.getName(), txt);
                return txt.toString();

            } else if (ActiveTempPrelimNmPdfExtractor.getFileNameMatcher(item.getName()).matches()) {
                // Active P&T NM PDF
                StringBuilder txt = new StringBuilder();
                updateActiveNm(item.getInputStream(), item.getName(), txt);
                return txt.toString();
            }
        }
    }

    return "No valid PDF uploaded";
}

From source file:helma.util.MimePart.java

/**
 * Creates a new MimePart object from a file upload.
 * @param fileItem a commons fileupload file item
 *//*  w  w  w  .j av  a2 s.c  om*/
public MimePart(FileItem fileItem) {
    name = normalizeFilename(fileItem.getName());
    contentType = fileItem.getContentType();
    contentLength = (int) fileItem.getSize();
    if (fileItem.isInMemory()) {
        content = fileItem.get();
    } else {
        this.fileItem = fileItem;
    }
}

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

/** {@inheritDoc} */
@Override/*  w ww . j  a  v  a 2 s  .c o m*/
public String getFilename(final String key) {
    final FileItem item = getFormItem(key);
    return (null == item) ? null : Resources.lastPart(item.getName());
}

From source file:com.alibaba.sample.petstore.biz.impl.StoreManagerImpl.java

private String getPictureName(FileItem picture) throws IOException {
    String imageFileName = null;/*from   w ww  . j a  v a 2 s.  c o m*/

    if (picture != null) {
        String fileName = picture.getName().replace('\\', '/');

        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);

        String ext = "";
        int index = fileName.lastIndexOf(".");

        if (index > 0) {
            ext = fileName.substring(index);
        }

        File imageFile = File.createTempFile("image_", ext, uploadDir);

        imageFileName = imageFile.getName();

        InputStream is = picture.getInputStream();
        OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile));

        StreamUtil.io(is, os, true, true);
    }

    return imageFileName;
}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

protected File createFile(File typeDir, FileItem item) throws IOException, FileNotFoundException {
    File f = new File(typeDir, item.getName());
    FileOutputStream fos = null;/*w w w  .j av a 2s  . com*/
    InputStream is = item.getInputStream();
    try {
        fos = new FileOutputStream(f);
        IOUtils.copyLarge(is, fos);
        return f;
    } finally {
        is.close();
        if (null != fos)
            fos.close();
    }
}

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name//from   www .j av a2  s.  c o  m
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}