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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:fina.usuario.servlet.usuarioServlet.java

private void modificarUsu(HttpServletRequest request, HttpServletResponse response,
        boolean modificarUsuarioSession) {

    JSONObject jsonResult = new JSONObject();
    Mensaje mensaje = new Mensaje(true, Mensaje.INFORMACION);
    boolean guardar = false;
    try {//from w w  w . j  ava  2 s  . com
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> listField = upload.parseRequest(request);
        Usuario usuario = new Usuario();
        UsuarioDao usuarioDao = new UsuarioDao();
        for (FileItem file : listField) {
            if (file.getFieldName().equals("txtNombres")) {
                usuario.setNombres(file.getString().trim());
            } else if (file.getFieldName().equals("txtApellidos")) {
                usuario.setApellidos(file.getString().trim());
            } else if (file.getFieldName().equals("txtFechaNacimiento")) {
                usuario.setFechaNacimiento(format.parse(file.getString().trim()));
            } else if (file.getFieldName().equals("txtUsuario")) {
                usuario.setUsername(file.getString().trim());
            } else if (file.getFieldName().equals("txtContrasenia")) {
                usuario.setContrasenia(file.getString());
            } else if (file.getFieldName().equals("rbSexo")) {
                usuario.setSexo("M".equals(file.getString()));
            } else if (file.getFieldName().equals("txtFoto")) {
                byte[] imagen = file.get();
                if (imagen != null && imagen.length > 0) {
                    usuario.setFoto(imagen);
                    usuario.setNombreFoto(file.getName());
                } else {
                    Usuario actual = usuarioDao.Obtener(usuario.getIdUSUARIO());
                    if (actual != null) {
                        usuario.setFoto(actual.getFoto());
                        usuario.setNombreFoto(actual.getNombreFoto());
                    }
                }
            } else if (file.getFieldName().equals("txtDNI")) {
                usuario.setDni(file.getString().trim());
            } else if (file.getFieldName().equals("tipoUsuario")) {
                Tipousuario tipou = usuarioDao.getTipousuarioById(file.getString().trim());
                usuario.setIdTipoUsuario(tipou);
            } else if (file.getFieldName().equals("txtIdUsuario")) {
                usuario.setIdUSUARIO(Integer.valueOf(file.getString().isEmpty() ? "-1" : file.getString()));
            } else if (file.getFieldName().equals("txtEstado")) {
                usuario.setEliminado(Boolean.valueOf(file.getString()));
            } else if (file.getFieldName().equals("txtGuardarUsuario")) {
                guardar = Boolean.valueOf(file.getString());
            }
        }
        if (usuario.getSexo() == null) {
            usuario.setSexo(true);
        }
        if (guardar) {
            usuario.setIdUSUARIO(null);
            usuarioDao.Insertar(usuario);
        } else {
            usuarioDao.Actualizar(usuario);
        }

        if (modificarUsuarioSession) {
            request.getSession().setAttribute("usuarioLogeado", usuario);
        }
        mensaje.setMensaje("Se registro correctamente.");

    } catch (Exception ex) {
        mensaje.establecerError(ex);
    }
    try {
        JSONObject jsonMensaje = new JSONObject(mensaje);
        jsonResult.put("msj", jsonMensaje);
        enviarDatos(response, jsonResult.toString());
    } catch (Exception ex) {
    }
}

From source file:calliope.handler.put.AesePutHandler.java

private void parseRequest(HttpServletRequest request) throws AeseException {
    try {// ww w  .  java2  s .  c o m
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }
            } else if (item.getName().length() > 0) {
                byte[] rawData = item.get();
                guessEncoding(rawData);
                if (encoding == null)
                    encoding = guessEncoding(rawData);
                fileContent = new String(rawData, encoding);
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

public Hashtable getHashtable(HttpServletRequest request) throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {//from w  w w  .j  a  v a  2  s . c  o m
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}

From source file:juzu.plugin.upload.impl.UploadPlugin.java

public void invoke(Request request) {

    ///*  ww w . ja  v  a  2 s  .  c o m*/
    final ClientContext clientContext = request.getClientContext();

    //
    if (clientContext != null) {
        String contentType = clientContext.getContentType();
        if (contentType != null) {
            if (contentType.startsWith("multipart/")) {

                //
                org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() {
                    public String getCharacterEncoding() {
                        return clientContext.getCharacterEncoding();
                    }

                    public String getContentType() {
                        return clientContext.getContentType();
                    }

                    public int getContentLength() {
                        return clientContext.getContentLenth();
                    }

                    public InputStream getInputStream() throws IOException {
                        return clientContext.getInputStream();
                    }
                };

                //
                FileUpload upload = new FileUpload(new DiskFileItemFactory());

                //
                try {
                    List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx);
                    HashMap<String, RequestParameter> parameters = new HashMap<String, RequestParameter>();
                    for (FileItem file : list) {
                        String name = file.getFieldName();
                        if (file.isFormField()) {
                            RequestParameter parameter = parameters.get(name);
                            if (parameter != null) {
                                parameter = parameter.append(new String[] { file.getString() });
                            } else {
                                parameter = RequestParameter.create(name, file.getString());
                            }
                            parameter.appendTo(parameters);
                        } else {
                            ControlParameter parameter = request.getMethod().getParameter(name);
                            if (parameter instanceof ContextualParameter
                                    && FileItem.class.isAssignableFrom(parameter.getType())) {
                                request.setArgument(parameter, file);
                            }
                        }
                    }

                    // Keep original parameters that may come from the request path
                    for (RequestParameter parameter : request.getParameters().values()) {
                        if (!parameters.containsKey(parameter.getName())) {
                            parameter.appendTo(parameters);
                        }
                    }

                    // Redecode phase arguments from updated request
                    Method<?> method = request.getMethod();
                    Map<ControlParameter, Object> arguments = method.getArguments(parameters);

                    // Update with existing contextual arguments
                    for (Map.Entry<ControlParameter, Object> argument : request.getArguments().entrySet()) {
                        if (argument.getKey() instanceof ContextualParameter) {
                            arguments.put(argument.getKey(), argument.getValue());
                        }
                    }

                    // Replace all arguments
                    request.setArguments(arguments);
                } catch (FileUploadException e) {
                    throw new UndeclaredThrowableException(e);
                }
            }
        }
    }

    //
    request.invoke();
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.UploadImageFileServlet.java

/**
 * Overridden doPost method./*from w w w.j a  va 2s. c  om*/
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String batchClassId = null;
    String docName = null;
    String fileName = null;
    String isAdvancedTableInfo = null;
    InputStream instream = null;
    OutputStream out = null;
    PrintWriter printWriter = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        String uploadPath = null;
        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {

                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("batchClassID")) {
                        batchClassId = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("docName")) {
                        docName = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("isAdvancedTableInfo")) {
                        isAdvancedTableInfo = item.getString();
                    }
                } else if (!item.isFormField() && "importFile".equals(item.getFieldName())) {
                    fileName = item.getName();
                    if (fileName != null) {
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                    }
                    instream = item.getInputStream();
                }
            }
            if (batchClassId == null || docName == null) {
                LOG.error(
                        "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: "
                                + batchClassId + " Doc Type :: " + docName);
                printWriter.write("Error while loading image... Either batchClassId or doc type is null.");
            } else {
                StringBuilder uploadPathString = uploadPath(batchClassId, docName, isAdvancedTableInfo,
                        batchSchemaService);
                File uploadFolder = new File(uploadPathString.toString());
                if (!uploadFolder.exists()) {
                    try {
                        boolean tempPath = uploadFolder.mkdirs();
                        if (!tempPath) {
                            LOG.error(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            printWriter.write(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            return;
                        }
                    } catch (Exception e) {
                        LOG.error("Unable to create the folders in the temp directory.", e);
                        printWriter
                                .write("Unable to create the folders in the temp directory." + e.getMessage());
                        return;
                    }
                }
                uploadPathString.append(File.separator);
                uploadPathString.append(fileName);
                uploadPath = uploadPathString.toString();
                out = new FileOutputStream(uploadPath);
                byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE];
                int len = instream.read(buf);
                while ((len) > 0) {
                    out.write(buf, 0, len);
                    len = instream.read(buf);
                }
                // convert tiff to png
                ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class);
                imageProcessService.generatePNGForImage(new File(uploadPath));
                LOG.info("Png file created successfully for file: " + uploadPath);
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        } catch (DCMAException e) {
            LOG.error("Unable to generate PNG." + e, e);
            printWriter.write("Unable to generate PNG.Please try again.");
        } finally {
            if (out != null) {
                out.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        printWriter.write("file_seperator:" + File.separator);
        printWriter.write("|");
    }
}

From source file:com.mockey.ui.UploadConfigurationServlet.java

/**
 * /*  ww w .  j av a2s  .  c om*/
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String url = null;
    String definitionsAsString = null;
    String taglistValue = "";

    // ***********************************
    // STEP #1 - READ DATA
    // ***********************************
    if (req.getParameter("viaUrl") != null) {
        url = req.getParameter("url");
        taglistValue = req.getParameter("taglist");
        try {
            InputStream fstream = new URL(url).openStream();
            if (fstream != null) {

                BufferedReader br = new BufferedReader(
                        new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8)));
                StringBuffer inputString = new StringBuffer();
                // Read File Line By Line
                String strLine = null;
                // READ FIRST
                while ((strLine = br.readLine()) != null) {
                    // Print the content on the console
                    inputString.append(new String(strLine.getBytes(HTTP.UTF_8)));
                }
                definitionsAsString = inputString.toString();
            }
        } catch (Exception e) {
            logger.error("Unable to reach url: " + url, e);
            Util.saveErrorMessage("Unable to reach url: " + url, req);
        }
    } else {
        byte[] data = null;
        try {
            // STEP 1. GATHER UPLOADED ITEMS
            // Create a new file upload handler
            DiskFileUpload upload = new DiskFileUpload();

            // Parse the request
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {

                    data = item.get();

                } else {

                    String name = item.getFieldName();
                    if ("taglist".equals(name)) {
                        taglistValue = item.getString();
                    }

                }
            }
            if (data != null && data.length > 0) {
                definitionsAsString = new String(data);
            }
        } catch (Exception e) {
            logger.error("Unable to read or parse file: ", e);
            Util.saveErrorMessage("Unable to upload or parse file.", req);
        }
    }

    // ***********************************
    // STEP #2 - PERSIST DATA
    // ***********************************
    try {

        if (definitionsAsString != null) {
            MockeyXmlFileManager configurationReader = new MockeyXmlFileManager();
            ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString,
                    taglistValue);

            Util.saveSuccessMessage("Service definitions uploaded.", req);
            req.setAttribute("conflicts", results.getConflictMsgs());
            req.setAttribute("additions", results.getAdditionMessages());
        } else {
            Util.saveErrorMessage("Unable to upload or parse empty file.", req);
        }
    } catch (Exception e) {
        Util.saveErrorMessage("Unable to upload or parse file.", req);
    }

    RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp");
    dispatch.forward(req, resp);
}

From source file:admin.controller.ServletEditPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w .j  av a  2 s  . com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BRAND_IMAGES_HOME;
        deletePath = AppConstants.BRAND_IMAGES_HOME;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("brandname")) {
                        brandname = fi.getString();
                    }
                    if (fieldName.equals("brandid")) {
                        brandid = fi.getString();
                    }
                    if (fieldName.equals("look")) {
                        lookid = fi.getString();
                    }

                    file_name_to_delete = brand.getFileName(Integer.parseInt(brandid));
                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    //                        int inStr = fileName.indexOf(".");
                    //                        String Str = fileName.substring(0, inStr);
                    //
                    //                        fileName = brandname + "_" + Str + ".jpeg";
                    fileName = brandname + "_" + fileName;
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String file_path = uploadPath + File.separator + fileName;
                    String delete_path = deletePath + File.separator + file_name_to_delete;
                    File deleteFile = new File(delete_path);
                    deleteFile.delete();
                    File storeFile = new File(file_path);
                    fi.write(storeFile);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName);
            response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        out.close();
    }

}

From source file:admin.controller.ServletUpdateFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w.  j  av  a  2s  . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = "";
    RequestDispatcher request_dispatcher;
    String fontname = null, fontid = null, lookid;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH;
        deletePath = AppConstants.BASE_FONT_UPLOAD_PATH;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("fontname")) {
                        fontname = fi.getString();
                    }
                    if (fieldName.equals("fontid")) {
                        fontid = fi.getString();
                        file_name_to_delete = font.getFileName(Integer.parseInt(fontid));
                    }

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    if (fileName != "") {

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = uploadPath + File.separator + fileName;
                        String delete_path = deletePath + File.separator + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            font.changeFont(Integer.parseInt(fontid), fontname, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while Updating fonts", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:it.univaq.servlet.Upload_rist.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map rist = new HashMap();
    //prendo id pubblicazione dalla request

    if (ServletFileUpload.isMultipartContent(request)) {
        Map files = new HashMap();
        int idpubb = Integer.parseInt(request.getParameter("id"));
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*/* w  w w . j  a va 2 s  .c o  m*/
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapub")) {
                    rist.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
                //prendo id del file se  stato inserito
                ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                if (!isNull(rs1)) {
                    while (rs1.next()) {
                        rist.put("download", rs1.getInt("id"));
                    }
                }

            }

        }

        rist.put("idpub", idpubb);
        //inserisco dati in tab ristampa
        Database.insertRecord("ristampa", rist);

        return true;
    } else
        return false;
}

From source file:com.baobao121.baby.common.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 * /* w  w w.  ja v a 2s . c o  m*/
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();
    String currentPath = "";
    String currentDirPath = "";
    String typeStr = request.getParameter("Type");
    UserCommonInfo info = null;
    info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO);
    if (info == null) {
        info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO);
    }
    currentPath = baseDir + "images/";
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) {
        currentPath += "admin/";
    } else {
        if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) {
            currentPath += "babyInfo/";
        }
        if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) {
            currentPath += "teacherInfo/";
        }
    }
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    currentPath += info.getId();
    currentDirPath = getServletContext().getRealPath(currentPath);
    if (!(new File(currentDirPath).isDirectory())) {
        new File(currentDirPath).mkdir();
    }
    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            upload.setHeaderEncoding("utf-8");
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");

            String fileNameLong = uplFile.getName();
            InputStream is = uplFile.getInputStream();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];
            Calendar calendar = Calendar.getInstance();
            String nameWithoutExt = String.valueOf(calendar.getTimeInMillis());
            ;
            String ext = getExtension(fileName);
            fileName = nameWithoutExt + "." + ext;
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName);
                changeDimension(is, desc, 450, 1000);
                if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) {
                    Photo photo = new Photo();
                    photo.setPhotoName(fileName);
                    PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName());
                    if (album.getId() != null) {
                        Long albumId = album.getId();
                        photo.setPhotoAlbumId(albumId);
                        photo.setPhotoLink(fileUrl);
                        photo.setDescription("");
                        photo.setReadCount(0L);
                        photo.setCommentCount(0L);
                        photo.setReadPopedom("1");
                        photo.setCreateTime(DateUtil.getCurrentDateTimestamp());
                        photo.setModifyTime(DateUtil.getCurrentDateTimestamp());
                        babyPhotoDao.save(photo);
                        babyAlbumDao.updateAlbumCount(albumId);
                    }
                }
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("?: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "??";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','"
            + newName + "','" + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}