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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream 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:etc.CloudStorage.java

/**
 *
 * This upload method expects a file and simply displays the file in the
 * multipart upload again to the user (in the correct mime encoding).
 *
 *
 * @return/*from w w w. ja v  a2  s . c o  m*/
 * @throws Exception
 * @param context
 */
public Mp3 uploadMp3(Context context) throws Exception {
    // make sure the context really is a multipart context...
    Mp3 mp3 = null;
    if (context.isMultipart()) {
        // This is the iterator we can use to iterate over the contents of the request.
        try {
            FileItemIterator fileItemIterator = context.getFileItemIterator();

            while (fileItemIterator.hasNext()) {
                FileItemStream item = fileItemIterator.next();
                String name = item.getName();

                // Store audio file
                GcsFilename filename = new GcsFilename("musaemachine.com", name);
                // Store generated waveform image
                GcsFilename waveImageFile = new GcsFilename("musaemachine.com",
                        removeExtension(name).concat(".png"));

                InputStream stream = item.openStream();

                String contentType = item.getContentType();
                System.out.println("--- " + contentType);
                GcsFileOptions options = new GcsFileOptions.Builder().acl("public-read").mimeType(contentType)
                        .build();

                byte[] audioBuffer = getByteFromStream(stream);

                GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, options);

                outputChannel.write(ByteBuffer.wrap(audioBuffer));
                outputChannel.close();

                //  AudioWaveformCreator awc = new AudioWaveformCreator(); 

                // byte[]waveform=   awc.createWavForm(stream);
                //   System.out.println("Buff Image---- "+waveform);
                // Saving waveform image
                //                    GcsOutputChannel waveFormOutputChannel =
                //                            gcsService.createOrReplace(waveImageFile, options);
                //                    waveFormOutputChannel.write(ByteBuffer.wrap(audioBuffer));
                //                    waveFormOutputChannel.close();
                //                    

                BodyContentHandler handler = new BodyContentHandler();
                ParseContext pcontext = new ParseContext();
                Metadata metadata = new Metadata();
                mp3Parser.parse(stream, handler, metadata, pcontext);

                Double duration = Double.parseDouble(metadata.get("xmpDM:duration"));
                mp3 = new Mp3(name, duration);

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

From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    String dest = req.getParameter(DEST_PARAM);
    String preload = req.getParameter(PRELOAD_PARAM);
    String overrideCacheKey = req.getParameter(CACHE_KEY);
    String fileType = req.getParameter(FILE_TYPE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", "");
    }//from   w w w .jav  a 2s  .co m
    StopWatch.getInstance().start("Upload File");

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        if (!item.isFormField()) {
            String fileName = item.getName();
            InputStream inStream = new BufferedInputStream(item.openStream(),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            String ext = resolveExt(fileName);
            FileType fType = resolveType(fileType, ext, item.getContentType());
            File destDir = resolveDestDir(dest, fType);
            boolean doPreload = resolvePreload(preload, fType);

            File uf = File.createTempFile("upload_", ext, destDir);
            String rPathInfo = ServerContext.replaceWithPrefix(uf);

            UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType());
            String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo;
            UserCache.getInstance().put(new StringKey(fileCacheKey), fi);

            if (doPreload && fType == FileType.FITS) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf),
                        IpacTableUtil.FILE_IO_BUFFER_SIZE);
                TeeInputStream tee = new TeeInputStream(inStream, bos);
                try {
                    final Fits fits = new Fits(tee);
                    FitsRead[] frAry = FitsRead.createFitsReadArray(fits);
                    FitsCacher.addFitsReadToCache(uf, frAry);
                } finally {
                    FileUtil.silentClose(bos);
                    FileUtil.silentClose(tee);
                }
            } else {
                FileUtil.writeToFile(inStream, uf);
            }
            sendReturnMsg(res, 200, null, fileCacheKey);
            Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType());
            return;
        }
    }
    StopWatch.getInstance().printLog("Upload File");
}

From source file:com.jythonui.server.upload.UpLoadFile.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();

    IAddNewBlob addB = SHolder.getAddBlob();

    PrintWriter out = response.getWriter();
    boolean first = true;
    try {/*w ww.j  a va  2 s  .  com*/
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            // only uploaded files
            if (item.isFormField())
                continue;

            String fName = item.getName();
            // nothing uploaded
            if (CUtil.EmptyS(fName))
                continue;
            InputStream stream = item.openStream();
            // may be set initial size not default
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len;
            while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
                bout.write(buffer, 0, len);
            }
            bout.close();
            // store blob content
            String bkey = addB.addNewBlob(ICommonConsts.BLOBUPLOAD_REALM, ICommonConsts.BLOBUPLOAD_KEY,
                    bout.toByteArray());
            if (!first)
                out.print(',');
            first = false;
            out.print(ICommonConsts.BLOBUPLOAD_REALM);
            out.print(':');
            out.print(bkey);
            out.print(':');
            out.print(fName);
        } // while

    } catch (Exception e) {
        out.print(ICommonConsts.UPLOADFILEERROR);
        IGetLogMess iLog = SHolder.getM();
        String mess = iLog.getMess(IErrorCode.ERRORCODE77, ILogMess.ERRORWHILEUPLOADING);
        log.log(Level.SEVERE, mess, e);
    }
    out.close();

}

From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java

/**
 * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String, UploadProgress)
 *///from  w  w w .j av  a2  s .  c  o m
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex,
        final UploadProgress progress) throws Exception {
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();

    final DiskFileItemFactory itemFactory = new DiskFileItemFactory();
    itemFactory.setRepository(getDiskCacheLocation());
    itemFactory.setSizeThreshold(getMemoryCacheThreshold());

    String encoding = conn.getRequest().getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }

    final ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding(encoding);
    upload.setProgressListener(new UploadProgressListener(progress));

    long sizeLimit = uploadSelect.getUploadSizeLimit();
    if (sizeLimit == 0)
        sizeLimit = getFileUploadSizeLimit();
    if (sizeLimit != NO_SIZE_LIMIT) {
        upload.setSizeMax(sizeLimit);
    }

    String fileName = null;
    String contentType = null;

    try {
        final FileItemIterator iter = upload.getItemIterator(conn.getRequest());
        if (iter.hasNext()) {
            final FileItemStream stream = iter.next();

            if (!stream.isFormField()) {
                fileName = FilenameUtils.getName(stream.getName());
                contentType = stream.getContentType();

                final Set<String> types = uploadSelect.getContentTypeFilter();
                if (!types.isEmpty()) {
                    if (!types.contains(contentType)) {
                        app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable(
                                uploadSelect, uploadIndex, fileName, contentType, progress));
                        return;
                    }
                }

                progress.setStatus(Status.inprogress);
                final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName());
                item.getOutputStream(); // initialise DiskFileItem internals

                uploadSelect.notifyCallback(
                        new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize()));

                IOUtils.copy(stream.openStream(), item.getOutputStream());

                app.enqueueTask(uploadSelect.getTaskQueue(),
                        new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress));

                return;
            }
        }

        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new RuntimeException("No multi-part content!"), progress));
    } catch (final FileUploadBase.SizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final FileUploadBase.FileSizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final MultipartStream.MalformedStreamException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress));
    }
}

From source file:es.eucm.mokap.backend.controller.insert.MokapInsertController.java

/**
 * Stores an uploaded file with a temporal file name.
 * //  www.j ava 2s  .c o  m
 * @param fis
 *            Stream with the file
 * @return Name of the created temporal file
 * @throws IOException
 *             if the file name is null, or if it has no zip extension
 */
private String storeUploadedTempFile(FileItemStream fis) throws IOException {
    String tempFileName;
    // Let's process the file
    String fileName = fis.getName();
    if (fileName != null) {
        fileName = FilenameUtils.getName(fileName);
    } else {
        throw new IOException(ServerReturnMessages.INVALID_UPLOAD_FILENAMEISNULL);
    }

    if (!fileName.toLowerCase().endsWith(UploadZipStructure.ZIP_EXTENSION)) {
        throw new IOException(ServerReturnMessages.INVALID_UPLOAD_EXTENSION);
    } else {
        InputStream is = fis.openStream();
        // Calculate fileName
        tempFileName = Utils.generateTempFileName(fileName);
        // Actually store the general temporal file
        st.storeFile(is, tempFileName);
        is.close();
    }
    return tempFileName;
}

From source file:com.example.getstarted.basicactions.UpdateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");

    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;/*from  w w w .j a v a  2  s .  c om*/
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    try {
        Book oldBook = dao.readBook(Long.decode(params.get("id")));

        Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
                .publishedDate(params.get("publishedDate")).title(params.get("title"))
                .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl)
                .id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy())
                .createdById(oldBook.getCreatedById()).build();

        dao.updateBook(book);
        resp.sendRedirect("/read?id=" + params.get("id"));
    } catch (Exception e) {
        throw new ServletException("Error updating book", e);
    }
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;//from  w  w  w. j a v  a2 s . c  o  m
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

/**
 * Tests, whether an {@link InvalidFileNameException} is thrown.
 *//*from w  ww  .  j a v a  2s  .  co  m*/
public void testInvalidFileNameException() throws Exception {
    final String fileName = "foo.exe\u0000.png";
    final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\""
            + fileName + "\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n"
            + "This is the content of the file\n" + "\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"field\"\r\n" + "\r\n" + "fieldValue\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value1\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value2\r\n" + "-----1234--\r\n";
    final byte[] reqBytes = request.getBytes("US-ASCII");

    FileItemIterator fileItemIter = parseUpload(reqBytes.length, new ByteArrayInputStream(reqBytes));
    final FileItemStream fileItemStream = fileItemIter.next();
    try {
        fileItemStream.getName();
        fail("Expected exception");
    } catch (InvalidFileNameException e) {
        assertEquals(fileName, e.getName());
        assertTrue(e.getMessage().indexOf(fileName) == -1);
        assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1);
    }

    List<FileItem> fileItems = parseUpload(reqBytes);
    final FileItem fileItem = fileItems.get(0);
    try {
        fileItem.getName();
        fail("Expected exception");
    } catch (InvalidFileNameException e) {
        assertEquals(fileName, e.getName());
        assertTrue(e.getMessage().indexOf(fileName) == -1);
        assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1);
    }
}

From source file:foo.domaintest.http.HttpApiModuleTest.java

FileItemStream createItem(String name, String value, boolean isFormField) throws Exception {
    FileItemStream item = mock(FileItemStream.class);
    when(item.isFormField()).thenReturn(isFormField);
    when(isFormField ? item.getFieldName() : item.getName()).thenReturn(name);
    // Use UTF_16 and specify it to provideParameterMap to make sure we honor the request encoding.
    when(item.openStream()).thenReturn(new ByteArrayInputStream(value.getBytes(UTF_16)));
    return item;/*from   w w w. j a  v  a  2  s.co m*/
}

From source file:de.mpg.imeji.presentation.upload.UploadServlet.java

/**
 * Download the file on the disk in a tmp file
 *
 * @param req//from ww w .j av  a2s  . c o m
 * @return
 * @throws FileUploadException
 * @throws IOException
 */
private UploadItem doUpload(HttpServletRequest req) {
    try {
        final ServletFileUpload upload = new ServletFileUpload();
        final FileItemIterator iter = upload.getItemIterator(req);
        UploadItem uploadItem = new UploadItem();
        while (iter.hasNext()) {
            final FileItemStream fis = iter.next();
            if (!fis.isFormField()) {
                uploadItem.setFilename(fis.getName());
                final File tmp = TempFileUtil.createTempFile("upload", null);
                StorageUtils.writeInOut(fis.openStream(), new FileOutputStream(tmp), true);
                uploadItem.setFile(tmp);
            } else {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                StorageUtils.writeInOut(fis.openStream(), out, true);
                uploadItem.getParams().put(fis.getFieldName(), out.toString("UTF-8"));
            }
        }
        return uploadItem;
    } catch (final Exception e) {
        LOGGER.error("Error file upload", e);
    }
    return new UploadItem();
}