Upload de arquivo

1 resposta
J

Pessoal,

Estou tentando fazer apload de um arquivo utilizando ajax, so q estou com alguns problemas:
P.S.: Tirei algumas verificações do codigo [como if ( request.getMethod() == “POST” && FileUpload.isMultipartContent(request) ) {], para facilitar os teste…

<h2>CADASTRO DE ALUNOS</h2>
<form name="CADALUNO" id="cadastro" method="post" action="../controlador.jsp" onsubmit="return cadastro('../controlador.jsp',this,'CONFIG_USUARIO');">
    <br/><br/>
	<fieldset id="aluno"> 
		<legend>Dados do Aluno</legend>
  		<input name="COCODIGOUSUARIO" value="<%=session.getAttribute("USCODIGO").toString()%" type="hidden">
  		<label for="nome">Nome:</label>
			<input type="text" tabindex="1" value="" name="nome" maxlength="60" class="nome"> 
		<span class="visivel"> 
			<span class="tab">
				<label for="turma">Turma:</label>
				<select name="turma" class="par" tabindex="2">
					<option value="Educação">Educação Infantil</option>
					<option value="Ensino Fundamental">Ensino Fundamental</option>
				</select>	
			</span>	
			<span class="tab">		
				<label for="serie">Série:</label>
				<select name="serie" class="par" tabindex="3">
					<option value="Maternal I">Maternal I</option>
					<option value="Maternal II">Maternal II</option>
					<option value="Jardim I">Jardim I</option>					
					<option value="Jardim II">Jardim II</option>					
					<option value="Jardim III">Jardim III</option>					
					<option value="1ª Série">1ª <!--ª-->Série</option>					
					<option value="2ª Série">2ª Série</option>					
					<option value="3ª Série">3ª Série</option>					
					<option value="4ª Série">4ª Série</option>					
				</select> 
			</span> 
			<span class="tab">
				<label for="horario">Horário:</label>
				<select name="horario"  class="par" tabindex="4">
					<option value="Vespertino"> Vespertino</option>
					<option value="Matutino"> Matutino</option>
				</select> 
			</span> 
			<span class="tab">
                            <label for="aniv">Aniversário:</label>
                            <input value="01/01/2007" name="aniv" size="21" maxlength="10" tabindex="5">
                        </span> 
                        <span class="tab">
                            <label for="profe">Professor(es):</label>
                            <a  id="prof" class="vprof" href="#" name="profe">Lista professor(es) da turma:
                                <span>
                                    João Batista da Silva - Matemática <br/>
                                    Jean Carlos Coelho de Alencar - informatica <br>
                                    João Batista da Silva nunes - Português <br/>
                                    João Batista da Silva - Educação Fisica
                                </span>
                            </a>
                        </span> 
                            <span id="vfoto" class="tab">                
                            <label for="foto">Foto:</label>
                            <a href="#" class="lfoto"> Visualizar Foto:                                
                                <span><img id="foto" src="imagens/boneco.png"/></span>
                            </a> </label>
                            <input type="file" name="foto" id="foto" size="45" 
                                tabindex="6" onchange="chamaFoto('jsp/restr/uploadFoto.jsp',this,'lfoto','vfoto')"/>

                        </span>    
                    </span>

                </fieldset> 
                <div id="botao" >
                    <button type="submit" ><img src="imagens/salvar.png" ></button>
                     &nbsp
                    <button type="reset" ><img src="imagens/cancel.jpg"></button>                        
                </div>
        </form>
<input type="file" name="foto" id="foto" size="45" 
                                tabindex="6" onchange="chamaFoto('jsp/restr/uploadFoto.jsp',this,'lfoto','vfoto')"/>

JSP

<%@ page import="org.apache.commons.fileupload.*,java.util.*,java.io.*" %>
<%System.out.println("entrou"); 

   DiskFileUpload upload = new DiskFileUpload();

   // faz o parsing da requisição 
   try{
   List items = upload.parseRequest(request);
  System.out.println("passou1"); //tirar
   // e iterage sobre o resultado
   Iterator itr = items.iterator();

   while(itr.hasNext()) {
      FileItem item = (FileItem) itr.next();
      // checa se item é um campo normal ou arquivo sendo feito upload
      boolean isFormField = item.isFormField();
        System.out.println(isFormField); //tirar
      if ( !isFormField ) {
	 String nomeArquivo = item.getName();
         // grava o arquivo no diretório /upload do contexto web (note que esse diretório
	 // deve existir)
         String path = getServletContext().getRealPath("/") + "jsp/restr/fotos/" + nomeArquivo;
	 try {
	    File file = new File( path );
	    item.write( file ); 
	    out.println("jsp/restr/fotos/" + nomeArquivo); 


	 } catch( IOException exc ) {
	    out.println( "Erro gravando arquivo: " + exc.getMessage() );
	 }
         
      } // if isFormField
        else{
        System.out.println("negativo");
        }
   } // while
}catch(Exception e){
            System.out.println(e.toString()); //tirar         
         }
%>

E JS

function chamaFoto(controlador,arquivo,idLink, idAvo){
	var vfoto = document.getElementById(idAvo);
        var foto = vfoto.getElementsByTagName("img") ;
	var link = vfoto.getElementsByTagName("a");
        link[0].className = 'lfoto';
        foto[0].setAttribute("src",gravaFoto(controlador,arquivo));
}

function gravaFoto(paginaResult,arquivo){
	if(xmlHttp) {
		var query = encodeURIComponent(arquivo.name) + "=" + encodeURIComponent(arquivo.value);
                var nomeArquivo = "";
	    xmlHttp.open("POST", paginaResult, true);
		xmlHttp.setRequestHeader("Content-Type","multipart/mixed stream");

		xmlHttp.onreadystatechange = function( ) {
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
                                        nomeArquivo = xmlHttp.responseText;
                   		}
                }
	}
        }
	xmlHttp.send(query); 
	return nomeArquivo;
}

ele apresenta o seguinte erro:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Obs.: chamando direto sem o ajax tá funcionando!!

T+
JC

1 Resposta

H

Veja se esses links podem te ajudar…

http://swik.net/DWR+upload

Esse é bem explicativo…

http://www.telio.be/blog/2006/01/06/ajax-upload-progress-monitor-for-commons-fileupload-example/

Abraços

Criado 9 de abril de 2007
Ultima resposta 18 de abr. de 2007
Respostas 1
Participantes 2