Upload File

82 views
Skip to first unread message

Leonardo Terrão

unread,
Mar 2, 2012, 8:26:28 AM3/2/12
to Google Web Toolkit
Hello everybody!

Following are some examples found right here in the discussion group
took two classes below.

In my class I have ArquivoUpload umTextBox a form with a ListBox and a
FileUpload. In class FileUploadServlet're getting only the data from
the FileUpload. Could someone help me also take the data from the
TextBox?
In debug mode I see everything that is in the form of the request but
I can not extract the values​​.

public class ArquivoUpload implements EntryPoint {

public static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL()
+ "upload";

@Override
public void onModuleLoad() {

// Cria um FormPanel e apontá-lo para um serviço.
final FormPanel form = new FormPanel();
form.setAction(UPLOAD_ACTION_URL);

// Porque nós vamos adicionar um widget FileUpload, vamos precisar
para
// definir o
// Form usar o método POST, e codificação MIME multipart.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);

// Cria um painel para conter todos os elementos do formulário.
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);

// Criar um TextBox, dando-lhe um nome para que ele será submetido.
final TextBox tb = new TextBox();
tb.setName("TextBoxFormElement");
panel.add(tb);

// Criar um ListBox, dando-lhe um nome e alguns valores que devem
ser
// associados
// Com suas opções.
ListBox lb = new ListBox();
lb.setName("listBoxFormElement");
lb.addItem("foo", "fooValue");
lb.addItem("bar", "barValue");
lb.addItem("baz", "bazValue");
panel.add(lb);

// Criar um widget FileUpload.
final FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);

panel.add(new UploadForm());

// Adicionar um botão 'Enviar'.
panel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
}));

//Adicionar um manipulador de eventos para o formulário.
form.addSubmitHandler(new FormPanel.SubmitHandler() {

@Override
public void onSubmit(SubmitEvent event) {

if (upload.getFilename().equals("")) {
event.cancel();
return;
}

//Este evento é disparado pouco antes do formulário é submetido.
//Podemos aproveitar esta oportunidade para realizar a validação.
String filename= upload.getFilename();
int index = filename.lastIndexOf(".");
String ext = filename.substring(index + 1);
if (!(ext.equals("gif") || ext.equals("jpg") || ext.equals("GIF")
|| ext.equals("JPG"))){
Window.alert("Extensão de arquivo inválida. Por favor adicione
apenas arquivos com extensões .jpg ou .gif.");
event.cancel();
}
}
});

form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler()
{
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
///Quando o envio do formulário é concluída com êxito,
//este evento é acionado. Assumindo que o serviço retornou
//uma resposta do tipo text / html, podemos obter o texto
resultado aqui
//(consulte a documentação FormPanel para mais explicações).
Window.alert(event.getResults());
System.out.println(event.getResults());
}
});
RootPanel rootPanel = RootPanel.get();
rootPanel.add(form);
}
}



public class FileUploadServlet extends HttpServlet {

private static final String UPLOAD_DIRECTORIY = "C:\\uploaded\\";

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException {
super.doGet(req, resp);
}

@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException {

// processar apenas as solicitações de várias
if (ServletFileUpload.isMultipartContent(req)) {

// Criar uma fábrica de artigos baseados em disco de arquivos
FileItemFactory factory = new DiskFileItemFactory();

// Crie um manipulador de novo upload de arquivos
ServletFileUpload upload = new ServletFileUpload(factory);

// Analisar o pedido
try {

List<FileItem> items = upload.parseRequest(req);

for (FileItem item : items) {

// processo só upload de arquivo - descartar outros tipos de
// item do form
if (item.isFormField()) continue;

// pega o nome do arquivo
String fileName = item.getName();

// pega extensão do arquivo
int index = fileName.lastIndexOf(".");
String ext = fileName.substring(index + 1);
ext = "." + ext;
System.out.println(ext);

// obter apenas o nome do arquivo não o caminho todo
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}

File uploadedFile = new File(UPLOAD_DIRECTORIY, fileName);
if (uploadedFile.createNewFile()) {
item.write(uploadedFile);
resp.setStatus(HttpServletResponse.SC_CREATED);
resp.getWriter().println("O arquivo foi criado com sucesso.");
resp.flushBuffer();
} else
throw new IOException(
"O arquivo já existe no repositório.");
}

} catch (Exception e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Ocorreu um erro ao criar o arquivo: " + e.getMessage());
}

} else {
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"Tipo de conteúdo pedido não é suportado pelo servlet.");
}
}
}


Thank you!

Jim Douglas

unread,
Mar 2, 2012, 2:33:29 PM3/2/12
to Google Web Toolkit
Hi Leonardo,

I use Apache FileUpload to manage the process:

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

Here's the doPost() method from my FileUploadServelet:

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

/*
* This tracks the state of the upload progress. The client
will
* occasionally request a progress update; the doGet() method
* returns this information to the client in an XML structure.
*/
FileUploadProgress progress = new FileUploadProgress();
HttpSession session = p_request.getSession();
session.setAttribute("progress", progress);
upload.setProgressListener(progress);

try
{
FileItemIterator iter = upload.getItemIterator(p_request);
StringBuilder response = new StringBuilder();
Integer id = null;
while (iter.hasNext())
{
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField())
{
String value = Streams.asString(stream);
if ("id".equals(name))
{
id = Integer.valueOf(value);
}
if ("saveAs".equals(name))
{
if (id == null)
{

p_response.sendError(SC_INTERNAL_SERVER_ERROR,
"No filesystem id for " + name + " " +
value);
return;
}
File f =
ClientFileSystemBridge.createTempFile(value);
ClientFileSystemBridge.put(id, value, f);
}
response.append(name).append(' ')
.append(value).append('\n');
}
else
{
String filename = item.getName();
if (id == null)
{
p_response.sendError(SC_INTERNAL_SERVER_ERROR,
"No filesystem id for file " + filename);
return;
}
File f =
ClientFileSystemBridge.createTempFile(filename);
OutputStream out = new FileOutputStream(f);
try
{
// This WILL fail with
org.mortbay.jetty.EofException
// if the client form disappears before we've
read the
// entire stream.
int bytes;
byte buf[] = new byte[32768];
while ((bytes = stream.read(buf)) > 0)
out.write(buf, 0, bytes);
}
catch (Throwable t)
{
p_response.sendError(SC_INTERNAL_SERVER_ERROR,
t.getClass().getName() + " " +
t.getMessage());
t.printStackTrace();
}
finally
{
out.close();
stream.close();
}
ClientFileSystemBridge.put(id, filename, f);
response.append(name).append(' ').
append(f.length()).append(' ').
append(filename).append('\n');
}
}
String message = response.toString();
p_response.reset();
p_response.setContentType("text/plain");
p_response.setContentLength(message.length());
Writer writer = p_response.getWriter();
writer.append(message);
writer.flush();
}
// catch (FileUploadException e)
// {
// p_response.sendError(SC_INTERNAL_SERVER_ERROR,
e.getMessage());
// e.printStackTrace();
// }
catch (Throwable e)
{
p_response.sendError(SC_INTERNAL_SERVER_ERROR,
e.getMessage());
e.printStackTrace();
}
}

And a helper function for reporting progress:

import org.apache.commons.fileupload.ProgressListener;

public class FileUploadProgress implements ProgressListener
{
private volatile long m_bytesRead;
private volatile long m_contentLength;
private volatile int m_item;

public FileUploadProgress()
{
super();
}

public void update(long p_bytesRead, long p_contentLength, int
p_item)
{
m_bytesRead = p_bytesRead;
m_contentLength = p_contentLength;
m_item = p_item;
}

public long getBytesRead()
{
return m_bytesRead;
}

public long getContentLength()
{
return m_contentLength;
}

public int getItem()
{
return m_item;

Thad

unread,
Mar 2, 2012, 3:45:41 PM3/2/12
to google-we...@googlegroups.com
I agree with Jim on using Apache FileUpload.

One trick I occasionally use to simplify my upload processing for text fields is to create a hidden field within the form. Before calling form.submit(), I do whatever validation and format conversions I want and assemble the non-file input into a JSON string that I assign to my hidden field. With this method I can submit values from fields outside of the FormPanel and greater control over the fields inside the panel.

Alfredo Quiroga-Villamil

unread,
Mar 2, 2012, 3:49:28 PM3/2/12
to google-we...@googlegroups.com
If your backend is Spring they also have great support for this. A few lines only and you are up and running.


Best regards,

Alfredo

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To view this discussion on the web visit https://groups.google.com/d/msg/google-web-toolkit/-/REsNwDkw_v0J.
To post to this group, send email to google-we...@googlegroups.com.
To unsubscribe from this group, send email to google-web-tool...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.



--
Alfredo Quiroga-Villamil

AOL/Yahoo/Gmail/MSN IM:  lawwton


Leonardo Terrão

unread,
Mar 5, 2012, 7:09:49 AM3/5/12
to Google Web Toolkit
Thanks guys!

Jim, the class is also ClientFileSystemBridge Apache FileUpload?

Thank you!

On 2 mar, 17:49, Alfredo Quiroga-Villamil <laww...@gmail.com> wrote:
> If your backend is Spring they also have great support for this. A few
> lines only and you are up and running.
>
> http://www.ioncannon.net/programming/975/spring-3-file-upload-example/
>
> Best regards,
>
> Alfredo
>
>
>
>
>
>
>
> On Fri, Mar 2, 2012 at 3:45 PM, Thad <thad.humphr...@gmail.com> wrote:
> > I agree with Jim on using Apache FileUpload.
>
> > One trick I occasionally use to simplify my upload processing for text
> > fields is to create a hidden field within the form. Before calling
> > form.submit(), I do whatever validation and format conversions I want and
> > assemble the non-file input into a JSON string that I assign to my hidden
> > field. With this method I can submit values from fields outside of the
> > FormPanel and greater control over the fields inside the panel.
>
> > On Friday, March 2, 2012 2:33:29 PM UTC-5, Jim Douglas wrote:
>
> >> Hi Leonardo,
>
> >> I use Apache FileUpload to manage the process:
>

> >>http://commons.apache.org/**fileupload/<http://commons.apache.org/fileupload/>


>
> >> Here's the doPost() method from my FileUploadServelet:
>
> >>     @Override
> >>     public void doPost(HttpServletRequest p_request,
> >>                        HttpServletResponse p_response)
> >>         throws ServletException, IOException
> >>     {
> >>         ServletFileUpload upload = new ServletFileUpload();
>
> >>         /*
> >>          * This tracks the state of the upload progress. The client
> >> will
> >>          * occasionally request a progress update; the doGet() method
> >>          * returns this information to the client in an XML structure.
> >>          */
> >>         FileUploadProgress progress = new FileUploadProgress();
> >>         HttpSession session = p_request.getSession();

> >>         session.setAttribute("**progress", progress);
> >>         upload.setProgressListener(**progress);
>
> >>         try
> >>         {
> >>             FileItemIterator iter = upload.getItemIterator(p_**request);


> >>             StringBuilder response = new StringBuilder();
> >>             Integer id = null;
> >>             while (iter.hasNext())
> >>             {
> >>                 FileItemStream item = iter.next();
> >>                 String name = item.getFieldName();
> >>                 InputStream stream = item.openStream();
> >>                 if (item.isFormField())
> >>                 {
> >>                     String value = Streams.asString(stream);
> >>                     if ("id".equals(name))
> >>                     {
> >>                         id = Integer.valueOf(value);
> >>                     }
> >>                     if ("saveAs".equals(name))
> >>                     {
> >>                         if (id == null)
> >>                         {
>

> >> p_response.sendError(SC_**INTERNAL_SERVER_ERROR,


> >>                                 "No filesystem id for " + name + " " +
> >> value);
> >>                             return;
> >>                         }
> >>                         File f =

> >> ClientFileSystemBridge.**createTempFile(value);


> >>                         ClientFileSystemBridge.put(id, value, f);
> >>                     }
> >>                     response.append(name).append(' ')
> >>                             .append(value).append('\n');
> >>                 }
> >>                 else
> >>                 {
> >>                     String filename = item.getName();
> >>                     if (id == null)
> >>                     {

> >>                         p_response.sendError(SC_**INTERNAL_SERVER_ERROR,


> >>                             "No filesystem id for file " + filename);
> >>                         return;
> >>                     }
> >>                     File f =

> >> ClientFileSystemBridge.**createTempFile(filename);


> >>                     OutputStream out = new FileOutputStream(f);
> >>                     try
> >>                     {
> >>                         // This WILL fail with
> >> org.mortbay.jetty.EofException
> >>                         // if the client form disappears before we've
> >> read the
> >>                         // entire stream.
> >>                         int bytes;
> >>                         byte buf[] = new byte[32768];
> >>                         while ((bytes = stream.read(buf)) > 0)
> >>                             out.write(buf, 0, bytes);
> >>                     }
> >>                     catch (Throwable t)
> >>                     {

> >>                         p_response.sendError(SC_**INTERNAL_SERVER_ERROR,


> >>                                 t.getClass().getName() + " " +
> >> t.getMessage());
> >>                         t.printStackTrace();
> >>                     }
> >>                     finally
> >>                     {
> >>                         out.close();
> >>                         stream.close();
> >>                     }
> >>                     ClientFileSystemBridge.put(id, filename, f);
> >>                     response.append(name).append(' ').
> >>                              append(f.length()).append(' ').

> >>                              append(filename).append('\n')**;


> >>                 }
> >>             }
> >>             String message = response.toString();
> >>             p_response.reset();

> >>             p_response.setContentType("**text/plain");
> >>             p_response.setContentLength(**message.length());


> >>             Writer writer = p_response.getWriter();
> >>             writer.append(message);
> >>             writer.flush();
> >>         }
> >> //        catch (FileUploadException e)
> >> //        {

> >> //            p_response.sendError(SC_**INTERNAL_SERVER_ERROR,


> >> e.getMessage());
> >> //            e.printStackTrace();
> >> //        }
> >>         catch (Throwable e)
> >>         {

> >>             p_response.sendError(SC_**INTERNAL_SERVER_ERROR,


> >> e.getMessage());
> >>             e.printStackTrace();
> >>         }
> >>     }
>
> >> And a helper function for reporting progress:
>

> >> import org.apache.commons.fileupload.**ProgressListener;

> >> >                 form.setAction(UPLOAD_ACTION_**URL);


>
> >> >                 // Porque nós vamos adicionar um widget FileUpload,
> >> vamos precisar
> >> > para
> >> >                 // definir o
> >> >                 // Form usar o método POST, e codificação MIME
> >> multipart.

> >> >                 form.setEncoding(FormPanel.**ENCODING_MULTIPART);
> >> >                 form.setMethod(FormPanel.**METHOD_POST);


>
> >> >                 // Cria um painel para conter todos os elementos do
> >> formulário.
> >> >                 VerticalPanel panel = new VerticalPanel();
> >> >                 form.setWidget(panel);
>
> >> >                 // Criar um TextBox, dando-lhe um nome para que ele
> >> será submetido.
> >> >                 final TextBox tb = new TextBox();

> >> >                 tb.setName("**TextBoxFormElement");


> >> >                 panel.add(tb);
>
> >> >                 // Criar um ListBox, dando-lhe um nome e alguns valores
> >> que devem
> >> > ser
> >> >                 // associados
> >> >                 // Com suas opções.
> >> >                 ListBox lb = new ListBox();

> >> >                 lb.setName("**listBoxFormElement");


> >> >                 lb.addItem("foo", "fooValue");
> >> >                 lb.addItem("bar", "barValue");
> >> >                 lb.addItem("baz", "bazValue");
> >> >                 panel.add(lb);
>
> >> >                 // Criar um widget FileUpload.
> >> >                 final FileUpload upload = new FileUpload();

> >> >                 upload.setName("**uploadFormElement");


> >> >                 panel.add(upload);
>
> >> >                 panel.add(new UploadForm());
>
> >> >                 // Adicionar um botão 'Enviar'.
> >> >                 panel.add(new Button("Submit", new ClickHandler() {
> >> >                         public void onClick(ClickEvent event) {
> >> >                                         form.submit();
> >> >                         }
> >> >                 }));
>
> >> >                 //Adicionar um manipulador de eventos para o formulário.
> >> >                 form.addSubmitHandler(new FormPanel.SubmitHandler() {
>
> >> >                         @Override
> >> >                         public void onSubmit(SubmitEvent event) {
>

> >> >                                 if (upload.getFilename().equals("**"))
> >> {
> >> >                                         event.cancel();
> >> >                                         return;
> >> >                                 }
>
> >> >                                 //Este
>
> ...
>
> mais »

Jim Douglas

unread,
Mar 5, 2012, 12:35:18 PM3/5/12
to Google Web Toolkit
I posted this earlier, but I think I may have accidentally clicked
"Reply to author".

> Jim, the class is also ClientFileSystemBridge Apache FileUpload?

No, I didn't strip out all of my application-related code before I
posted it. Also, "id" and "saveAs" are just form names that I happen
to be using on the client side; your names will be different.

> > >> >                 // Criar um ListBox,...
>
> read more »

Reply all
Reply to author
Forward
0 new messages