Just an example that worked fine for me:

/*
 * File Upload - Arquivo de licitações - October, 2009.
 */
package servlets.comum;

import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Iterator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileItemFactory;
//import org.apache.commons.fileupload.FileItemIterator;
//import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
//import org.apache.commons.fileupload.util.Streams;

import comum.Arquivo;
import comum.ArquivoGestor;
//import comum.TipoArquivo;
import licitacao.Licitacao;
import comum.Usuario;

/**
 *
 * @author siomara
 */
public class MantemArquivo extends HttpServlet
{   
    // Process the HTTP GET request
    protected void doGet(HttpServletRequest request, HttpServletResponse
response)
    throws ServletException, IOException
    {
        doPost(request, response);
    } 

    protected void doPost(HttpServletRequest request, HttpServletResponse
response)
    throws ServletException, IOException
    {
        final int INSERT = 1;
        final int UPDATE = 2;
        final int DELETE = 3;

        // Retrieve operation to be performed
        int operation = Integer.parseInt(request.getParameter("op"));
        System.out.println("operation="+operation);
        
        // Create objects necessary to add/update/delete arquivo
        Arquivo arquivo = new Arquivo();
        ArquivoGestor arquivoGestor = new ArquivoGestor();
        
        // Set session true
        HttpSession session = request.getSession(true);
        
        Usuario usuarioAutenticado = (Usuario)
session.getAttribute("usuarioAutenticado");

        switch (operation)
        {
            case DELETE:
                
                // Retrieve from sessiom 'arquivo' to be deleted
                arquivo = (Arquivo) session.getAttribute("arquivo");

                // Delete 'arquivo'
                arquivoGestor.delete(arquivo);
    
                // Release resources
                arquivoGestor.releaseResources();
                
                // Here the delete is complete. Send user to
'exibeLicitacaoAdmin.jsp'
                RequestDispatcher dispatcher3 =
this.getServletContext().getRequestDispatcher("/licitacao/exibeLicitacaoAdmi
n.jsp");
                dispatcher3.forward(request, response);
                
                break;
                
            default:
 
                /**
                 * Default will perfom INSERT and UPDATE because these
operations have
                 * lots of things in commom. However be alert to their own
particularities. 
                 */
                
                // Create object to deal with dates
                DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                
                // Retrieve licitacao from the session for UPDATE operation
only
                if (operation == UPDATE) {
                    arquivo = (Arquivo) session.getAttribute("arquivo");
                }
                
                // Upload
                boolean isMultiPart =
ServletFileUpload.isMultipartContent(request);

                if (isMultiPart)
                {
                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new
ServletFileUpload(factory);
                    String formulario = "";

                    try
                    {
                        List items = upload.parseRequest(request);
                        Iterator iter = items.iterator();

                        while (iter.hasNext())
                        {
                            FileItem item = (FileItem) iter.next();

                            if (item.getFieldName().equals("tipoForm")) {
                                formulario = item.getString();
                            }
                            
                            If
(item.getFieldName().equals("txtTituloApresentacao")) {
 
arquivo.setTituloApresentacao(item.getString());
                            }
                            
                            if
(item.getFieldName().equals("txtNomeInterno")) {
                                arquivo.setNomeInterno(item.getString());
                            }
                            
                            if
(item.getFieldName().equals("cboTipoArquivo")) {
 
arquivo.getTipoArquivo().setTipoArquivoId(Integer.parseInt(item.getString())
);
                            }
                            
                            if
(item.getFieldName().equals("txtDataPublicacaoDou")) {
                                try
                                {
                                    java.util.Date data = new
java.sql.Date(dateFormat.parse(item.getString()).getTime());
                                    arquivo.setDataPublicacaoDou(data);
                                }
                                catch (ParseException e) {
e.printStackTrace(); }
                            }

                            if (!item.isFormField())
                            {
                                if (item.getName().length() > 0) {
this.inserirNoDiretorio(item); }
                            }
                        }
                    } 
                    catch (FileUploadException ex) { ex.printStackTrace(); }

                    catch (Exception ex) { ex.printStackTrace(); }
                }

                switch (operation)
                {
                    case INSERT:
                      
                        // Set primary key to zero. Sequence will be
incremented during add method
                        arquivo.setArquivoId(0);
                        
                        // Set register ID. Date will be registered on the
add method.
 
arquivo.getRegistro().setIncluidoPorId(usuarioAutenticado.getUsuarioId());
                        
                        // Add new arquivo to the database
                        arquivoGestor.add(arquivo);
               
                        Licitacao licitacao = new Licitacao();
                        licitacao = (Licitacao)
session.getAttribute("licitacao");
                        arquivoGestor.linkArquivoTolLicitacao(arquivo,
licitacao);
                        
                        // Release resources
                        arquivoGestor.releaseResources();                
 
                        // Here the registration is complete. Send user to
'exibeArquivo.jsp'
                        RequestDispatcher dispatcher =
this.getServletContext().getRequestDispatcher("/licitacao/exibeLicitacaoAdmi
n.jsp");
                        dispatcher.forward(request, response);
                        
                        break;
                        
                    case UPDATE:
                         
                        // Retrieve arquivo antigo from the session
                        arquivo = (Arquivo) session.getAttribute("arquivo");
                        
                        // Set register ID. Date will be registered on the
update method.
 
arquivo.getRegistro().setAlteradoPorId(usuarioAutenticado.getUsuarioId());
                        
                        // Update arquivo
                        arquivoGestor.update(arquivo);
    
                        // Release resources
                        arquivoGestor.releaseResources();
                
                        // Here the update is complete. Send user to
'exibeLicitacao.jsp'
                        RequestDispatcher dispatcher2 =
this.getServletContext().getRequestDispatcher("/licitacao/exibeLicitacaoAdmi
n.jsp");
                        dispatcher2.forward(request, response);

                        break;
                }
                break;
        }
    }
        /**
     * 
     * @param item FileItem, representa um arquivo que é enviado pelo
formulario
     * MultiPart/Form-data
     * @throws IOException
     */
    private void inserirNoDiretorio(FileItem item) throws IOException
    {
        //Pega o diretório /logo dentro do diretório atual de onde a
aplicação está rodando
        //String caminho = getServletContext().getRealPath("/logo") + "/";
        String caminho = "c:/psplicitacao" + "/";

         // Cria o diretório caso ele não exista
         File diretorio = new File(caminho);
         if (!diretorio.exists())
         {
             diretorio.mkdir();
         }
         
         // Mandar o arquivo para o diretório informado
         String nome = item.getName();
         String arq[] = nome.split("\\\\");
         for (int i = 0; i < arq.length; i++)
         {
             nome = arq[i]; 
         }
         File file = new File(diretorio, nome);
         FileOutputStream output = new FileOutputStream(file);
         InputStream is = item.getInputStream();
         byte[] buffer = new byte[2048];
         int nLidos;
         while ((nLidos = is.read(buffer)) >= 0)
         {
             output.write(buffer, 0, nLidos);
         }
         output.flush();
         output.close();
     }
 }



-----Mensagem original-----
De: jcar...@carmanconsulting.com [mailto:jcar...@carmanconsulting.com] Em
nome de James Carman
Enviada em: quarta-feira, 14 de outubro de 2009 08:57
Para: Commons Users List
Assunto: Re: File Upload

The parameters from your form aren't sent as usual when you use
multipart form data.  They are sent as "parts."  So, as you iterate
through the FileItem objects from your upload, some of them will be
form fields.  You can check by calling isFormField().  You can call
getFieldName() to get the field name and getString() to get the
field's value.  Check out this document for more information:

http://commons.apache.org/fileupload/using.html


On Wed, Oct 14, 2009 at 12:02 AM, Anand Shankar <anand.al....@gmail.com>
wrote:
> Hello
>
> I am facing more problem about File Upload and anybody is helping me. I
have
> listed my problem on all the open source forum, so please give me your
some
> important moment to suggest that how can I solve this problem.
>
>
> I am using a form with enctype="multipart/form-data" in order to upload
> files from the form.
> I have read this page: http://commons.apache.org/fileupload/using.html and
> everything works well for my form.
>
> The only problem is that I can't get all the values from a "multiple
select"
> html object. I get only one value.
>
> Using servlets I have used this method:
>
> *public* java.lang.String[] getParameterValues(java.lang.String name)
>
>
>
> But now I have enctype="multipart/form-data" in my form and I can't use
this
> way...
> Is there a way to get all the values of a multi-valued parameter?
>
>
> Thanks a lot!
>
> --
> Anand Shankar
>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscr...@commons.apache.org
For additional commands, e-mail: user-h...@commons.apache.org

Reply via email to