[Resolvido] Upload de vários arquivos criando diretório

3 respostas
D

Olá.

Estou com um probleminha aqui.
Criei este tópico no JavaFree também, pois preciso desta solução para concluir um projeto aqui.

Quando solicito o envio de arquivos criando um diretório para os mesmos, ocorre o erro no envio. O diretório é criado mas nenhum arquivo é enviado.

Fiz um teste simpes com apenas um arquivo e deu certo, mas com vários falhou.

Bom, vou explicar como é o processo: O diretório é criado com a data atual, mas esta data vem de uma consulta do banco de dados, após isso, cria-se o diretório com a data vinda da consulta e então o recebimento dos 5 arquivos para o diretório.

O código é o seguinte:
<%@page language="java" import="schema.Conexao"%>
<%@page contentType="text/html;charset=ISO-8859-1"%>
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%@page import="java.util.Date"%>
<%
   // session.getAttribute("adm001");

    String titleEvento = request.getParameter("titleTopic"); 
    String conteudoEvento = request.getParameter("richEdit0");

        String contentType = request.getContentType();
    
    if(titleEvento == null || titleEvento == "") {
        //session.setAttribute("tit", titleEvento);
        response.sendRedirect("new-evento.jsp?TituloVazio");
        return;
        } 
    if(titleEvento == "'") {
        response.sendRedirect("new-evento.jsp?invalido");
        }
    
    if (conteudoEvento == "") {
        response.sendRedirect("new-evento.jsp?ConteudoVazio");
        }
    
         
        
    Conexao c = new Conexao();  
   
   Connection conn = null; 
    conn = c.getConection();
   
   Statement stmt = null;
   
   try {  
       
       PreparedStatement pstmt = conn.prepareStatement("SELECT count(*) as topicos FROM tableTopic");
       ResultSet rs = pstmt.executeQuery();

       rs.next();
       
       int topico = Integer.parseInt(rs.getString("topicos"));
 
        int diretorio = topico+1;             
       
       
        stmt = conn.createStatement();
        stmt.execute("INSERT INTO tableTopic (codDiretorio, titleTopic, conteudoTopic, "+
                " EndDiretorio) VALUES ('"+diretorio+"', '"+titleEvento+"', '"+conteudoEvento+
                "', now() )");// WHERE adm001 == '"+adm001+"');"); 

        PreparedStatement pstmt1 =  conn.prepareStatement(
          "SELECT date_format(EndDiretorio, '%d-%m-%Y_%H-%i-%s') as data FROM tableTopic "+
          " WHERE codDiretorio='"+diretorio+"' and titleTopic = '"+titleEvento+"'");
        ResultSet rs1 = pstmt1.executeQuery();

       rs1.next(); 
       
     File dir = new File(application.getRealPath("/") + "/eventos/"+ rs1.getString("data"));
    if (dir.mkdir()) {

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                DataInputStream in = new DataInputStream(request.getInputStream());

                int formDataLength = request.getContentLength();

                byte dataBytes[] = new byte[formDataLength];

                int byteRead = 0;

                int totalBytesRead = 0;

              while (totalBytesRead < formDataLength) {

                  byteRead = in.read(dataBytes, totalBytesRead, formDataLength);

                     totalBytesRead += byteRead;

                }

                String file = new String(dataBytes);

                String saveFile = file.substring(file.indexOf("filename=\"") + 10);

              saveFile = saveFile.substring(0, saveFile.indexOf("\n"));

              saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");

                String boundary = contentType.substring(lastIndex + 1,contentType.length());

                int pos;

             pos = file.indexOf("filename=\"");

             pos = file.indexOf("\n", pos) + 1;

             pos = file.indexOf("\n", pos) + 1;

             pos = file.indexOf("\n", pos) + 1;

               int boundaryLocation = file.indexOf(boundary, pos) - 4;

                int startPos = ((file.substring(0, pos)).getBytes()).length;

                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                String filepath = dir+"/"+saveFile;

                FileOutputStream fileOut = new FileOutputStream(filepath);

            fileOut.write(dataBytes, startPos, (endPos - startPos));

            fileOut.flush();
            fileOut.close();

            out.println("diretório criado e imagens enviadas para<br>"+filepath);


  } else {
  	        out.println("erro ao enviar imagens para o diretório!");
  }

  }  else {
  	        out.println("erro ao criar diretório!");
  }

      } catch( SQLException sqlex) {
         out.println("Não foi possível criar o evento<br>" +sqlex);
         // session.putValue("erroCreate", "Nao foi possível criar o evento!");
         // response.sendRedirect("new-evento.jsp?erro");
      }         
                             
   
  %>

Postei o código completo. Também vão campos preenchidos, mas não tem muita importância, pois o problema é no recebimento das imagens.

Espero uma ajudinha nesse problema que está difícil de se resolver...

[]s

3 Respostas

D

O que tem de errado com meu código que eu não consigo enviar as imagens junto com o parâmetro id do tópico?

<%@page language="java" import="schema.Conexao"%>
<%@page contentType="text/html" pageEncoding="iso-8859-1"%>
<%@ page import="java.io.*"%>
<%@page import="java.sql.*"%>

<%
      String admin =  (String) session.getAttribute("logAceito");
      String id = request.getParameter("ok");

         if (admin == null) {
              response.sendRedirect("index.jsp");
            } else {


 out.println("id: "+id+"<br>");

        File dir = new File(application.getRealPath("/") + "/eventos\\");
   // if (dir.mkdir()) {

    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                DataInputStream in = new DataInputStream(request.getInputStream());

                int formDataLength = request.getContentLength();

                byte dataBytes[] = new byte[formDataLength];

                int byteRead = 0;

                int totalBytesRead = 0;

              while (totalBytesRead < formDataLength) {

                  byteRead = in.read(dataBytes, totalBytesRead, formDataLength);

                     totalBytesRead += byteRead;

                }

                String file = new String(dataBytes);

                String saveFile = file.substring(file.indexOf("filename=\"") + 10);

              saveFile = saveFile.substring(0, saveFile.indexOf("\n"));

              saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));

                int lastIndex = contentType.lastIndexOf("=");

                String boundary = contentType.substring(lastIndex + 1,contentType.length());

                int pos;

             pos = file.indexOf("filename=\"");

             pos = file.indexOf("\n", pos) + 1;

             pos = file.indexOf("\n", pos) + 1;

             pos = file.indexOf("\n", pos) + 1;

               int boundaryLocation = file.indexOf(boundary, pos) - 4;

                int startPos = ((file.substring(0, pos)).getBytes()).length;

                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

                String filepath = dir+"/"+saveFile;

                FileOutputStream fileOut = new FileOutputStream(filepath);

            fileOut.write(dataBytes, startPos, (endPos - startPos));

            fileOut.flush();
            fileOut.close();


         try {
              Connection conn = new Conexao().getConection();

               // gravando no banco de dados
              PreparedStatement pstmt =
              conn.prepareStatement("INSERT INTO images_001 (url_image) values ( ? )  WHERE codigoTopic = ? ");

              pstmt.setObject(1, saveFile);
              pstmt.setObject(2, id);

              pstmt.execute();

               } catch (SQLException sqlex) {
                  out.println("Não foi possível selecionar o nome do diretórios<br>" + sqlex);
                  sqlex.printStackTrace();
               }


               out.println("<h1>A imagem do upload foi: " + saveFile+"</h1>");
               out.println("<img src=\"eventos/" +saveFile+ "\" width=\"300\" height=\"300\" />");

            }
        //  }


    }   // fim do teste de admin on ou off

 %>

??

Se envio em modo get, a id é capturada e a imagem não é enviada.
Mas se envio como post, a imagem vai mas a id fica nula.

Já pensei em substituir pelo método de envio DiskFileUpload mas acho que não sei configurar para enviar para o classpath da aplicação.

<%@page language="java" import="org.apache.commons.fileupload.*, java.util.*, java.io.*" %>


<%
String site="localhost:8080/SITE/";
String caminhoTemp="/";
String pasta="/";

if (FileUpload.isMultipartContent(request)){
DiskFileUpload upload = new DiskFileUpload();
upload.setRepositoryPath(caminhoTemp);

try{
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {

String nome=item.getName().toString();
String nomeArquivo=nome.substring(nome.lastIndexOf("\\")+ 1);

out.write("nome do arquivo: " + nomeArquivo + "<br>");
out.write("Arquivo(s)<b> " +item.getName() +"</b> transferido(s)<br>");

File arquivo=new File(pasta+nomeArquivo);
item.write(arquivo);
out.write("Clique <a href=/testea/commons_FileUpload/"+ nomeArquivo +">Aqui</a>. Para ver o resultado do upload");
}
}
}catch(FileUploadException e){
out.write("Não foi possível efetivar o upload do arquivo - segue a causa do erro" + "<br>" + e.getMessage());
e.printStackTrace();
}
}

%>

?

D

Algum membro poderia me ajudar aqui com um servlet de upload?

No IE manda o nome de origem do arquivo (c://documents and settings…) e como faço para mandar o arquivo apenas com seu nome e não a origem?

Encontrei um exemplo que pensei que poderia resolver isso:
http://commons.apache.org/fileupload/faq.html#whole-path-from-IE

E aqui o exemplo que peguei e fiz o servlet:
http://www.roseindia.net/jsp/file_upload/employee_upload_profile_image.shtml

package uploader;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import schema.Conexao;
import java.sql.*;

public class createGallery extends HttpServlet {
    private String id = "";    
    private int count1 = 0;
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
             
       // int count1 = 0;
       
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
         if (!isMultipart) {
               // out.println("Erro ao enviar requisição!"); 
                     
	         if (!ServletFileUpload.isMultipartContent(request)) { 
                     String erro = request.getParameter("ok");
                        if (erro != null) {
                            response.sendRedirect("galery.jsp?ok="+erro+"&error=yes");
                        }
                 }
             
         } else {
             FileItemFactory factory = new DiskFileItemFactory();
             ServletFileUpload upload = new ServletFileUpload(factory);
             List items = null;
             try {
                 items = upload.parseRequest(request);
                 } catch (FileUploadException e) {
                 e.printStackTrace();
                 }
                 Iterator itr = items.iterator();
                 while (itr.hasNext()) 
              	   {
                 FileItem item = (FileItem) itr.next();
        
              if (item.isFormField()) {
	              String name = item.getFieldName();
		          String value = item.getString();
		          if(name.equals("ok")) {
			       id = value;
                              // out.println("A id do tópico é: "+value +"<br><br>");
            	               count1 = 1;
		              }
                     } else {
        
                     try {
                         String itemName = item.getName();
                           File savedFile = new File(getServletContext().getRealPath("/")+"eventos/"+itemName);
                            item.write(savedFile);  
     
                     if(count1 == 1) {     
                     Connection conn = Conexao.getConection();
                     
                     int codigo = Integer.parseInt(id);
                     
                     PreparedStatement inserirImagem = conn.prepareStatement(
                         "INSERT INTO images_001 (codigoTopic, url_image) VALUES (?, ?) ");
                      inserirImagem.setInt(1, codigo);
                      inserirImagem.setObject(2, itemName);
                      
                      inserirImagem.execute();
                      
                      //out.println("Imagem gravada no banco de dados com sucesso!");
                      //out.println("Código da página: "+codigo+"<br>A imagem enviada foi: "+itemName);

                      response.sendRedirect("galery.jsp?ok="+codigo+"&sucessfull=yes");
                      
                     }
                      
                     } catch(Exception ex) {
                         //ex.printStackTrace();
                         //out.println(ex);
                      response.sendRedirect("galery.jsp?ok="+id+"&exception=yes");   
                     } 
                         
                 }
             }
         } 
    } 

    // <editor-fold defaultstate="collapsed" desc="Métodos HttpServlet. Clique no sinal de + à esquerda para editar o código.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
D

Encontrei uma solução bem aqui:

http://www.javafree.org/viewtopic.jbb?t=871624

Puxa, era justo o que eu precisava

[]s

Criado 12 de dezembro de 2008
Ultima resposta 31 de dez. de 2008
Respostas 3
Participantes 1