Example usage for org.apache.commons.fileupload.servlet ServletFileUpload getHeaderEncoding

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getHeaderEncoding

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload getHeaderEncoding.

Prototype

public String getHeaderEncoding() 

Source Link

Document

Retrieves the character encoding used when reading the headers of an individual part.

Usage

From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java

/**
 * ?request?fireDir?request.setAttribute(fieldName, value)?
 *
 * @param request /*from  www  .ja va  2 s  .c  o m*/
 * @param fileDir 
 * @param maxSize ?
 * @param isFileNameBaseTime ????
 * @param encoding
 */
public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize,
        boolean isFileNameBaseTime, String encoding) {
    // ?
    if (!isFileUploadRequest(request))
        return null;
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // dir??
    File dir = new File(fileDir);
    if (!dir.exists()) {
        if (dir.mkdirs()) {
            throw new FileDirFaultException(dir);
        }
        ;
    }
    if (maxSize > 0) {
        factory.setSizeThreshold(maxSize);
    }

    factory.setRepository(dir);

    // ?
    ServletFileUpload fileUploader = new ServletFileUpload(factory);
    fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
    String realEncoding = fileUploader.getHeaderEncoding();

    List<FileItem> items = null;
    try {
        items = fileUploader.parseRequest(request);
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }
    if (items == null)
        return null;

    FileUploadRequestParamterContext context = new FileUploadRequestParamterContext();
    Map<String, List<File>> fileMap = context.getFileMap();
    Map<String, List<String>> fieldMap = context.getFormFieldMap();

    FileItem fileItem = null;
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        fileItem = iter.next();
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            List<String> values = fieldMap.get(fieldName);
            if (values == null) {
                values = new ArrayList<String>();
                fieldMap.put(fieldName, values);
            }
            String value = null;
            try {
                value = fileItem.getString(realEncoding);
            } catch (UnsupportedEncodingException e) {
                value = "";
                e.printStackTrace();
            }
            values.add(value);
            log.info("param:\t" + fieldName + "=" + value);
        } else {
            List<File> files = fileMap.get(fieldName);
            if (files == null) {
                files = new ArrayList<File>();
                fileMap.put(fieldName, files);
            }

            String clientFileName = fileItem.getName();// ???
            if (StringUtil.isNull(clientFileName)) { // 
                continue;
            }
            String realFileName = FileUtil.getRealFileName(clientFileName);
            String newFileName = null;
            if (isFileNameBaseTime) {
                newFileName = new FileNameBuilder().build(realFileName);
            } else {
                newFileName = realFileName;
            }
            File tempfile = new File(dir, newFileName);
            try {
                fileItem.write(tempfile);
                log.info("???\t" + newFileName);
                files.add(tempfile);
            } catch (Exception e) {
                continue;
            }
        }
    }

    return null;
}

From source file:n3phele.backend.RepoProxy.java

@POST
@Path("{id}/upload/{bucket}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket,
        @QueryParam("name") String destination, @QueryParam("expires") long expires,
        @QueryParam("signature") String signature, @Context HttpServletRequest request)
        throws NotFoundException {
    Repository repo = Dao.repository().load(id);
    if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(),
            bucket + ":" + destination)) {
        log.severe("Expired temporary authorization");
        throw new NotFoundException();
    }//from w  w  w .j a v a2  s  .  c  om

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding "
                + upload.getHeaderEncoding());
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (item.isFormField()) {
                log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream()));
            } else {
                InputStream stream = item.openStream();
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()
                        + " content " + item.getContentType());
                URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination);
                Response.created(target).build();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Processing error", e);
    }

    return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build();
}

From source file:servletExperimento.tratamento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww .jav 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession sessao = request.getSession(false);
    String tipo = (String) sessao.getAttribute("tipoTratamento");

    if (tipo.equals("adicionar")) {

        try {

            boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
            if (isMultiPart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                out.print(upload.getHeaderEncoding());
                upload.setHeaderEncoding("UTF-8");
                out.print(upload.getHeaderEncoding());
                List items;

                ArrayList<String> arquivos = new ArrayList<String>();

                String caminho = getServletContext().getRealPath("/experimentador/experimento/tecnica") + "/";

                items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                String desc = null, nome = null, tipoTec = null, art = null;
                while (iter.hasNext()) {

                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = new String(item.getString().getBytes("ISO-8859-1"), "UTF-8");

                        if (value.equals("") || value == null) {
                            response.sendRedirect("experimentador/experimento/plano_tecnica.jsp?msg=1");
                        } else {
                            if (name.equals("nome")) {
                                nome = value;
                            }
                            if (name.equals("descricao")) {
                                desc = value;
                            }
                            if (name.equals("tipo_tecnica")) {
                                tipoTec = value;
                            }
                            if (name.equals("rdArtefato")) {
                                art = value;
                            }
                            if (name.equals("idexperimento")) {
                                //                                    tecnica.setExperimento(Controladores.Controlador.getExperimentoAtual());
                                caminho = caminho + "tecnica_" + value + "/"; //?lvaro: 2\ -> /
                            }
                        }
                    } else {
                        if (!item.getName().equals("")) {
                            String path = new String();
                            path = item.getName();
                            this.inserirImagemDiretorio(item, caminho);
                            arquivos.add(path);
                        }
                    }
                }

                if (desc != null && nome != null) {

                    if (Controladores.Controlador.criarTratamento(nome, desc, tipoTec, art)) {
                        if (!arquivos.isEmpty()) {
                            int tam = arquivos.size();
                            for (int t = 0; t < tam; t++) {
                                ArquivoTratamento arq = new ArquivoTratamento();

                                //arq.setTratamento(tecnica); -> tecnica
                                //arq.setPath_arquivo(arquivos.get(t));
                                Controladores.Controlador.criarArquivoTratamento(
                                        Controladores.Controlador.listarTratamentos()
                                                .get(Controladores.Controlador.listarTratamentos().size() - 1),
                                        arquivos.get(t));
                            }
                        }
                        response.sendRedirect("experimentador/experimento/plano_tecnica.jsp?msg=0");
                    } else {
                        response.sendRedirect("experimentador/experimento/plano_tecnica.jsp?msg=2");
                    }

                }

            }

        } catch (FileUploadException ex) {
            Logger.getLogger(tratamento.class.getName()).log(Level.SEVERE, null, ex);

        } catch (Exception ex) {
            Logger.getLogger(tratamento.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

}