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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:dk.kontentsu.api.exposure.ItemExposure.java

private static InputStream getInputStream(final FileItem m) {
    try {/*from w  ww  .  j a v  a  2  s  .  c  om*/
        return m.getInputStream();
    } catch (IOException ex) {
        throw new ApiErrorException(
                "Error processing multipart data - unable to get input stream for reference " + m.getName(),
                ex);
    }
}

From source file:gov.nih.nci.caintegrator.application.lists.UserListGenerator.java

public static List<String> generateList(FileItem formFile) throws IOException {

    List<String> tempList = new ArrayList<String>();

    if ((formFile != null) && (formFile.getName().endsWith(".txt") || formFile.getName().endsWith(".TXT"))) {

        try {/*from   w  w  w .  jav a  2 s  .c o m*/
            InputStream stream = formFile.getInputStream();
            String inputLine = null;
            BufferedReader inFile = new BufferedReader(new InputStreamReader(stream));

            do {
                inputLine = inFile.readLine();

                if (inputLine != null) {
                    if (isAscii(inputLine)) { // make sure all data is ASCII                                                        
                        tempList.add(inputLine);
                    }
                } else {
                    System.out.println("null line");
                    while (tempList.contains("")) {
                        tempList.remove("");
                    }
                    inFile.close();
                    break;
                }

            } while (true);
        } catch (EOFException eof) {
            logger.error("Errors when reading empty lines in file:" + eof.getMessage());
        } catch (IOException ex) {
            logger.error("Errors when uploading file:" + ex.getMessage());
        }

    }

    return tempList;

}

From source file:Emporium.Controle.ContrDestinatarioImporta.java

public static String importaPedido(FileItem item, int idCliente, int idDepartamento, String nomeBD) {

    try {/*from w  w w  .j a va2 s. com*/
        //CONTADOR DE LINHA
        int qtdLinha = 1;
        ArrayList<ArquivoImportacao> listaAi = new ArrayList<ArquivoImportacao>();
        BufferedReader le = new BufferedReader(new InputStreamReader(item.getInputStream(), "ISO-8859-1"));
        // LE UMA LINHA DO ARQUIVO PARA PULAR O CABEALHO
        le.readLine();
        while (le.ready()) {
            //LE UMA LINHA DO ARQUIVO E DIVIDE A LINHA POR PONTO E VIRGULA
            String[] aux = le.readLine().replace(";", " ; ").split(";");
            //System.out.println("aaa "+aux[0]);
            //ADICIONA CONTADOR DE LINHA
            qtdLinha++;
            //VERIFICA QUANTIDADE MAXIMA DE LINHAS PERMITIDAS
            if (aux != null && aux.length >= 10) {

                ArquivoImportacao ai = new ArquivoImportacao();
                ai.setIdCliente(idCliente);
                ai.setIdDepartamento(idDepartamento);
                ai.setNrLinha(qtdLinha + "");
                ai.setNome(aux[0].trim());
                ai.setEmpresa(aux[1].trim());
                ai.setCpf(aux[2].trim());
                ai.setCep(aux[3].trim());
                ai.setEndereco(aux[4].trim());
                ai.setNumero(aux[5].trim());
                ai.setComplemento(aux[6].trim());
                ai.setBairro(aux[7].trim());
                ai.setCidade(aux[8].trim());
                ai.setUf(aux[9].trim());
                ai.setCelular("");
                if (aux.length >= 12 && aux[11] != null) {
                    ai.setCelular(aux[10].trim() + aux[11].trim());
                }
                ai.setEmail("");
                if (aux.length >= 13 && aux[12] != null) {
                    ai.setEmail(aux[12].trim());
                }
                ai.setObs("");//campo usado para tags (Entidade reaproveitada)
                if (aux.length >= 14 && aux[13] != null) {
                    ai.setObs(aux[13].trim());
                }

                listaAi.add(ai);

            }
        }
        le.close();

        if (listaAi.size() > 0) {
            //valida os dados do arquivo para efetuar a importacao
            listaAi = validaCepArquivo(listaAi);
            if (!falha.equals("")) {
                //retorna mensagem de falha
                return falha;
            } else {
                //MONTA SQL
                insereDestinatarios(listaAi, nomeBD);
                return "Destinatarios Importados Com Sucesso!";
            }
        } else {
            return "Nenhum pedido no arquivo para importar!";
        }

    } catch (IOException e) {
        return "No foi possivel ler o arquivo: " + e;
    } catch (Exception e) {
        return "Falha na importacao dos pedidos: " + e;
    }

}

From source file:br.edu.ifpb.sislivros.model.RequisicaoDeImg.java

public static void inserirImagem(FileItem item, String realPath, String nomeDaImagem) throws IOException {

    //Pegar o diretorio /imagensPerfil dentro do diretorio atual
    String diretorio = realPath + "/";

    //Criar diretorio caso no exista;
    File f = new File(diretorio);

    if (!f.exists()) {
        f.mkdir();//from w w  w . java2  s  .  co  m
    }

    //Mandar o arquivo para o diretorio informado
    f = new File(diretorio + nomeDaImagem + ".jpg");

    try {
        FileOutputStream output = new FileOutputStream(f);
        InputStream is = item.getInputStream();

        byte[] buffer = new byte[2048];

        int nLidos;

        while ((nLidos = is.read(buffer)) >= 0) {
            output.write(buffer, 0, nLidos);
        }

        output.flush();
    } finally {

    }

}

From source file:eml.studio.server.util.HDFSIO.java

/**
 * Upload file to HDFS//  ww w.  jav a 2  s.  c  om
 * @param uri target file path
 * @param item file to upload
 * @param name name of the new file
 * @throws IOException
 */
public static void uploadfile(String uri, FileItem item, String name) throws IOException {
    System.out.println("[dstPath]" + Constants.NAME_NODE + "/" + uri + name);
    FSDataOutputStream out = fs.create(new Path(Constants.NAME_NODE + uri + name));
    IOUtils.copyBytes(item.getInputStream(), out, 4096, true);
}

From source file:com.xpn.xwiki.web.Utils.java

/**
 * Get the content of an uploaded file, corresponding to the specified form field.
 * /*www  .j a  v a 2  s .c  om*/
 * @param filelist the list of uploaded files, computed by the FileUpload plugin
 * @param name the name of the form field
 * @return the content of the file, if the specified field name does correspond to an uploaded file, or {@code null}
 *         otherwise
 * @throws XWikiException if the file cannot be read due to an underlying I/O exception
 */
public static byte[] getContent(List<FileItem> filelist, String name) throws XWikiException {
    for (FileItem item : filelist) {
        if (name.equals(item.getFieldName())) {
            byte[] data = new byte[(int) item.getSize()];
            InputStream fileis = null;
            try {
                fileis = item.getInputStream();
                fileis.read(data);
            } catch (IOException e) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                        XWikiException.ERROR_XWIKI_APP_UPLOAD_FILE_EXCEPTION,
                        "Exception while reading uploaded parsed file", e);
            } finally {
                IOUtils.closeQuietly(fileis);
            }

            return data;
        }
    }

    return null;
}

From source file:com.silverpeas.gallery.MediaHelper.java

/**
 * Saves uploaded sound file on file system
 * @param fileHandler/*from   w w  w  .j  a v  a 2s .c o  m*/
 * @param sound the current sound media
 * @param fileItem the current uploaded sound
 * @throws Exception
 */
public static void processSound(final FileHandler fileHandler, Sound sound, final FileItem fileItem)
        throws Exception {
    if (fileItem != null) {
        String name = fileItem.getName();
        if (name != null) {
            try {
                sound.setFileName(FileUtil.getFilename(name));
                final HandledFile handledSoundFile = getHandledFile(fileHandler, sound);
                handledSoundFile.copyInputStreamToFile(fileItem.getInputStream());
                setInternalMetadata(handledSoundFile, sound, MediaMimeType.SOUNDS);
            } finally {
                fileItem.delete();
            }
        }
    }
}

From source file:com.silverpeas.gallery.MediaHelper.java

/**
 * Saves uploaded video file on file system
 * @param fileHandler//from  ww w . j  av  a 2  s  .  co m
 * @param video the current video media
 * @param fileItem the current uploaded video
 * @throws Exception
 */
public static void processVideo(final FileHandler fileHandler, Video video, final FileItem fileItem)
        throws Exception {
    if (fileItem != null) {
        String name = fileItem.getName();
        if (name != null) {
            try {
                video.setFileName(FileUtil.getFilename(name));
                final HandledFile handledVideoFile = getHandledFile(fileHandler, video);
                handledVideoFile.copyInputStreamToFile(fileItem.getInputStream());
                setInternalMetadata(handledVideoFile, video, MediaMimeType.VIDEOS);
                generateVideoThumbnails(handledVideoFile.getFile());
            } finally {
                fileItem.delete();
            }
        }
    }
}

From source file:com.silverpeas.gallery.MediaHelper.java

/**
 * Saves uploaded photo file on file system with associated thumbnails and watermarks.
 * @param fileHandler//from   ww w .j a v  a  2s .  c  o  m
 * @param photo
 * @param image
 * @param watermark
 * @param watermarkHD
 * @param watermarkOther
 * @throws Exception
 */
public static void processPhoto(final FileHandler fileHandler, final Photo photo, final FileItem image,
        final boolean watermark, final String watermarkHD, final String watermarkOther) throws Exception {
    if (image != null) {
        String name = image.getName();
        if (name != null) {
            try {
                photo.setFileName(FileUtil.getFilename(name));
                final HandledFile handledImageFile = getHandledFile(fileHandler, photo);
                handledImageFile.copyInputStreamToFile(image.getInputStream());
                if (setInternalMetadata(handledImageFile, photo, MediaMimeType.PHOTOS)) {
                    createPhoto(handledImageFile, photo, watermark, watermarkHD, watermarkOther);
                }
            } finally {
                image.delete();
            }
        }
    }
}

From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java

public static String updload(HttpServletRequest request, HttpServletResponse response, String autoPath,
        String showFileName) throws Exception {
    String message = "";

    // ?? /* w  w  w  .  j  a  va 2  s . c  o m*/
    File uploadPath = new File(autoPath);
    if (!uploadPath.exists()) {
        uploadPath.mkdir();
    }
    for (int i = 0; i < fi.size(); i++) {
        FileItem fileItem = fi.get(i);
        if (!fileItem.isFormField()) {
            //String fieldName = fileItem.getFieldName(); // ????file  inputname
            String fileName = fileItem.getName(); // file input??
            //String contentType = fileItem.getContentType(); // 
            //long size = fileItem.getSize(); // 

            String filePath = autoPath + File.separator + showFileName;
            // org.apache.commons.fileupload.FileItem ??write?
            // fileItem.write(new File(filePath));
            // ???? ? ?
            OutputStream outputStream = new FileOutputStream(new File(filePath));// ???
            InputStream inputStream = fileItem.getInputStream();
            int length = 0;

            byte[] buf = new byte[1024];
            while ((length = inputStream.read(buf)) != -1) { // ?????
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
            outputStream.close();
            message = "(" + fileName + ")?,??:" + filePath;
        }
    }
    return message;
}