2014-01-14 4 views
0

Ребята, я пытался загрузить файл с некоторыми данными, поступающими из полей формы, но мне не повезло, сервлет, который я использую здесь. Поскольку вы можете видеть, что for инициализируется if, это означает, что if работает нормально, но остальная часть conditional if игнорируется и данные не извлекаются или не отображаются (с out.print), поэтому я вставляю здесь код сервлета в надежде, что кто-то увидит, какие часы и часы я не мог видеть, пожалуйста, ребята, помогите мне с этим вопросом.Как получить входные данные из многостраничной формы в сервлете Java?

import DAO.CuentaCobroDAO; 
import DTO.CuentaCobroDTO; 
import DTO.contratoDTO; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.sql.SQLException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.List; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileItemFactory; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 

/** 
* 
* @author Leonardo 
*/ 
public class CuentaCobroCtrol extends HttpServlet { 

/** 
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
* methods. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException, FileUploadException, ParseException, SQLException { 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter out = response.getWriter(); 
    CuentaCobroDAO ccdao= new CuentaCobroDAO(); 
    CuentaCobroDTO cdto= new CuentaCobroDTO(); 
    contratoDTO con= new contratoDTO(); 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    FileItemFactory fif= new DiskFileItemFactory(); 
    ServletFileUpload sfu= new ServletFileUpload(fif); 
    String fechai="", fechaf=""; 
    String contrato, dias=null; 
    String valor, arl=null, eps=null, pension=null; 
    List items=sfu.parseRequest(request); 
    java.sql.Date fi, ff, factual; 
    Date fechaActual; 

    try{ 
    for (int i = 0; i < items.size(); i++) { 
     FileItem item = (FileItem) items.get(i); 

     if(item.isFormField()){ 

      if(item.getFieldName().equals("fechai")){ 
      fechai=obtenerDatoDeFormulario(item.getInputStream()); 
      out.print(fechai); 
      } 

      if(item.getFieldName().equals("fechaf")){ 
       fechaf=obtenerDatoDeFormulario(item.getInputStream()); 
       out.print("FECHAF"+fechaf); 
      } 


      if(item.getFieldName().equals("numcont")){ 
       contrato=obtenerDatoDeFormulario(item.getInputStream()); 
       out.print("CONTRATO"+contrato); 
      } 
      if(item.getFieldName().equals("dias")){ 
       dias=obtenerDatoDeFormulario(item.getInputStream()); 
       out.println(dias); 
      } 
      if(item.getFieldName().equals("valor")){ 
       valor=obtenerDatoDeFormulario(item.getInputStream()); 
       out.print(valor); 
      } 
      if(item.getFieldName().equals("arl")){ 
       arl=obtenerDatoDeFormulario(item.getInputStream()); 
       out.println("Por ARL:"+arl); 
      } 
      if(item.getFieldName().equals("eps")){ 
       eps=obtenerDatoDeFormulario(item.getInputStream()); 
       out.println("Por EPS:"+eps); 
      } 
      if(item.getFieldName().equals("pension")){ 
       pension=obtenerDatoDeFormulario(item.getInputStream()); 
       out.println("Por PENSION:"+pension); 
      } 

      out.print("El valor 2 de fecha I es:"+fechai); 

     } 
     /*   A continuación validamos que los campos que vienen del formulario no estén vacios, esto en caso de que javascript falle, 
     así garantizamos que tenemos todos los datos; hago esto antes de escribir el archivo en el servidor para evitar que se suba 
     información que está incompleta y no debe ser subida sino hasta que se compruebe que se tienen todos los datos.*/ 
     out.print("El valor 3 de fechai es:"+fechai+"el de final es:"+fechaf); 
      fechaActual= new Date(); 
      Date inicial=formatter.parse(fechai); 
      fi= new java.sql.Date(inicial.getTime()); 
      Date ffinal=formatter.parse(fechaf); 
      ff= new java.sql.Date(ffinal.getTime()); 
      factual=new java.sql.Date(fechaActual.getTime()); 
      out.print("El valor 4:"+fechai+"Y el de final es:"+fechaf); 
      if(fi.compareTo(factual)>0 || ff.compareTo(factual)>0){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg="+"Error, no puedes ingresar una cuenta del mes futuro o actual"); 
       break; 
      }else if(dias!=null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar los días trabajados"); 
       break; 
      }else if(30<Integer.parseInt(dias)){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= En el mes pueden ser máximo 30 días"); 
       break; 
      }else if(arl==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Tienes que ingresar el valor de la ARL"); 
       break; 
      }else if(eps==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Es necesario ingresar el valor de la EPS"); 
       break; 
      }else if(pension==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar el valor de pensión"); 
       break; 
      }else{ 
       String ruta="/archivos/pdf/"+request.getSession(false).getAttribute("iduser")+"/"; 
       String nombreArchivo=request.getSession(false).getAttribute("iduser")+"-"+factual; 
       if(!item.isFormField()){ 


        File archivoAServidor= new File(getServletContext().getRealPath(ruta+nombreArchivo)); 
        try { 
         item.write(archivoAServidor); 
        } catch (Exception ex) { 
         Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 
      cdto.setFinicial(fi); 
      cdto.setFfinal(ff); 
      cdto.setDias(Integer.parseInt(request.getParameter("dias"))); 
      cdto.setHoras(Integer.parseInt(request.getParameter("horas"))); 
      cdto.setPagoArl(Integer.parseInt(request.getParameter("arl"))); 
      cdto.setPagoEps(Integer.parseInt(request.getParameter("eps"))); 
      cdto.setPagoPension(Integer.parseInt(request.getParameter("pension"))); 
      cdto.setIdContratista((Integer)request.getSession(false).getAttribute("iduser")); 
      cdto.setValorAPagar(Integer.parseInt(request.getParameter("valor"))); 
      con.setIdCONTRATO((Integer)request.getSession(false).getAttribute("idContrato")); 
      cdto.setRutaDocumento(ruta+nombreArchivo); 
      String salida=cdto.insertCuenta(cdto, con); 
      response.sendRedirect("nomina/cuentacobro.jsp?msg="+salida); 
      } 
    } 
    }catch(IOException iex){ 
     throw iex; 
    }catch(ParseException pex){ 
     throw pex; 
    } 






    try { 
     /* TODO output your page here. You may use following sample code. */ 
     out.println("<!DOCTYPE html>"); 
     out.println("<html>"); 
     out.println("<head>"); 
     out.println("<title>Servlet CuentaCobroCtrol</title>");    
     out.println("</head>"); 
     out.println("<body>"); 
     out.println("<h1>Servlet CuentaCobroCtrol at " + request.getContextPath() + "</h1>"); 
     out.println("</body>"); 
     out.println("</html>"); 
    } finally { 
     out.close(); 
    } 
} 

private static String obtenerDatoDeFormulario(InputStream is){ 
    BufferedReader br=null; 
    StringBuilder sb= new StringBuilder(); 

    String linea; 


    try { 
     br= new BufferedReader(new InputStreamReader(is)); 
     while((linea=br.readLine())!= null){ 
      sb.append(linea); 
     } 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally{ 
     if(br!=null){ 
      try { 
       br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 
    } 

    return sb.toString(); 

} 


// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
/** 
* Handles the HTTP <code>GET</code> method. 
* 
* @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 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    try { 
     processRequest(request, response); 
    } catch (FileUploadException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (ParseException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (SQLException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

/** 
* Handles the HTTP <code>POST</code> method. 
* 
* @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 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    try { 
     processRequest(request, response); 
    } catch (FileUploadException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (ParseException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (SQLException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

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

} 

PD: out.print используются для отображения информации, собранной из Фиэль, но после того, как первый Если обрабатывается, то остальные просто игнорируются.

ответ

0

Ну ребята afther думать в течение долгого долгого времени, у меня была гениальная искра и, наконец, понял, что происходит с этим servelet так explenation здесь:

Елки я должен сказать, что в начале я не мог» t понимать, как данные передаются сервлету, когда форма является многочастной, поэтому здесь была огромная ошибка, мы должны понять, что каждое отдельное поле формы будет обращено как элемент, поэтому для формы, которую я использовал, у меня было 9 поля, так что cicle будет работать 10 раз, и вот была ошибка, если вы проанализируете мой первый сервлет, вы обнаружите, что я использовал if (9 раз), а затем вложенный, если был синтаксический анализ даты, и здесь все не так путь, потому что, когда игла повторяется над каждым найденным предметом, тогда он будет оценивать все найденные там на теле o f для так, что только с первым cicle у меня есть уникальное исключение даты, и здесь ничего не работает, поэтому имейте в виду, что при выполнении cicles даже с Iterator или для каждого он будет запускать количество раз, равное количеству элементов, оценивающих что внутри цикле, будьте осторожны, какие условия вы оцениваете и как вы это делаете. Поэтому здесь я поставлю правильный сервлет, который сделает именно то, что я хочу, и это: получите содержимое полей формы, затем получите файл на сервере, напишите его и, наконец, сохраните информацию для поля формы на база данных. Здесь вы найдете сервлет (оправдание, если какой-то код сбивает с толку, это может быть причиной написано на испанском языке)

package controlador; 

import DAO.CuentaCobroDAO; 
import DTO.CuentaCobroDTO; 
import DTO.contratoDTO; 
import java.sql.SQLException; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.io.File; 
import java.io.PrintWriter; 
import java.util.List; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileItemFactory; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 
import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.util.Calendar; 


/** 
* 
* @author Leonardo 
*/ 
public class CuentaCobroCtrol extends HttpServlet { 

/** 
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> 
* methods. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException, FileUploadException, ParseException, SQLException { 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter out = response.getWriter();     
    String fechaIni=""; 
    String fechaFin=""; 
    String contrato=""; 
    String valorArl=""; 
    String valorEps=""; 
    String valorPension=""; 
    String valorAPagar=""; 
    String numeroDias=""; 
    String ruta=""; 
    String nombreArchivo=""; 
    String timeStamp=""; 
    boolean suceed=false; 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    CuentaCobroDAO ccdao= new CuentaCobroDAO(); 
    CuentaCobroDTO cdto= new CuentaCobroDTO(); 
    contratoDTO con= new contratoDTO(); 


    FileItemFactory ff = new DiskFileItemFactory(); 



    ServletFileUpload sfu = new ServletFileUpload(ff); 



    List items = sfu.parseRequest(request); 
    java.sql.Date fi=null, fif=null, factual=null; 
    Date fechaActual; 

    try{ 


     for(int i=0;i<items.size();i++){ 



     FileItem item = (FileItem) items.get(i); 

     if (item.isFormField()){ 

         /*   A continuación validamos que los campos que vienen del formulario no estén vacios, esto en caso de que javascript falle, 
     así garantizamos que tenemos todos los datos; hago esto antes de escribir el archivo en el servidor para evitar que se suba 
     información que está incompleta y no debe ser subida sino hasta que se compruebe que se tienen todos los datos.*/ 
      if(item.getFieldName().equals("numcont")){ 
       contrato=getStringFromInputStream(item.getInputStream()); 
       out.print("<br/> el valor de numero es: "+contrato); 
      } 
      if(item.getFieldName().equals("dias")){ 
       numeroDias=getStringFromInputStream(item.getInputStream()); 
       out.print(" <br/> el valor de dias es: "+numeroDias); 
       if(numeroDias==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar los días trabajados"); 
       break;}else if(30<Integer.parseInt(numeroDias)){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= En el mes pueden ser máximo 30 días"); 
       break; 
      } 
      } 
      if(item.getFieldName().equals("valor")){ 
       valorAPagar=getStringFromInputStream(item.getInputStream()); 
       out.print(" <br/> el valor es: "+valorAPagar); 
       if(Integer.parseInt(valorAPagar)<=0 || valorAPagar==null){ 
        response.sendRedirect("nomina/cuentacobro.jsp?msg= El valor no puede ser nagativo o nulo. Por favor ingresa el valor a pagar"); 
       } 
      } 
      if(item.getFieldName().equals("arl")){ 
       valorArl=getStringFromInputStream(item.getInputStream()); 
       out.print(" <br/> el valor de arl es: "+valorArl); 
       if(valorArl==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Tienes que ingresar el valor de la ARL"); 
       break; 
      } 
      } 
      if(item.getFieldName().equals("eps")){ 
       valorEps=getStringFromInputStream(item.getInputStream()); 
       out.print(" <br/> el valor de eps es: "+valorEps); 
       if(valorEps==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Es necesario ingresar el valor de la EPS"); 
       break; 
      } 
      } 
      if(item.getFieldName().equals("pension")){ 
       valorPension=getStringFromInputStream(item.getInputStream()); 
       out.print(" <br/> el valor de pension es: "+valorPension); 
       if(valorPension==null){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Debes ingresar el valor de pensión"); 
       break; 
      } 
      } 
      if(item.getFieldName().equals("fechai")) 
     { 
      fechaIni=getStringFromInputStream(item.getInputStream()); 
      out.print("el valor de fechaInicial es: "+fechaIni); 
      if(fechaIni==null || fechaIni.length()<4){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg= Error, no ingresaste el valor de fecha periodo inicial"); 
      } 
     } 
      if(item.getFieldName().equals("fechaf")){ 
       fechaFin=getStringFromInputStream(item.getInputStream()); 
       fechaActual= new Date(); 
      Date inicial=formatter.parse(fechaIni); 
      fi= new java.sql.Date(inicial.getTime()); 
      Date ffinal=formatter.parse(fechaFin); 
      fif= new java.sql.Date(ffinal.getTime()); 
      factual=new java.sql.Date(fechaActual.getTime()); 
      if(fi.compareTo(factual)>0 || fif.compareTo(factual)>0){ 
       response.sendRedirect("nomina/cuentacobro.jsp?msg="+"Error, no puedes ingresar una cuenta del mes futuro o actual"); 
       break; 
      } 

      } 
    } 

     if(!item.isFormField()){ 
       timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()); 
       ruta="/archivos/pdf/"+request.getSession(false).getAttribute("iduser")+"/"; 
       nombreArchivo=request.getSession(false).getAttribute("iduser")+"-"+timeStamp+".pdf"; 
        File dir=new File(ruta+nombreArchivo); 
        dir.mkdirs(); 
        File archivoAServidor= new File(getServletContext().getRealPath(ruta+nombreArchivo)); 

        try { 
         item.write(archivoAServidor); 
         suceed=true; 
        } catch (Exception ex) { 
         Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
        } 
       } 
    } 
    if(suceed==true){ 
     cdto.setFinicial(fi); 
      cdto.setFfinal(fif); 
      cdto.setDias(Integer.parseInt(numeroDias)); 
      cdto.setHoras(Integer.parseInt("0")); 
      cdto.setPagoArl(Integer.parseInt(valorArl)); 
      cdto.setPagoEps(Integer.parseInt(valorEps)); 
      cdto.setPagoPension(Integer.parseInt(valorPension)); 
      cdto.setIdContratista((Integer)request.getSession(false).getAttribute("iduser")); 
      cdto.setValorAPagar(Integer.parseInt(valorAPagar)); 
      con.setIdCONTRATO((Integer)request.getSession(false).getAttribute("idContrato")); 
      cdto.setRutaDocumento(ruta+nombreArchivo); 
      String salida=cdto.insertCuenta(cdto, con); 
      response.sendRedirect("nomina/cuentacobro.jsp?msg="+salida); 
    } 



    }catch(IOException iex){ 
     throw iex; 
    }catch(ParseException pex){ 
     throw pex; 
    } 






    try { 
     /* TODO output your page here. You may use following sample code. */ 
     out.println("<!DOCTYPE html>"); 
     out.println("<html>"); 
     out.println("<head>"); 
     out.println("<title>Servlet CuentaCobroCtrol</title>");    
     out.println("</head>"); 
     out.println("<body>"); 
     out.println("<h1>Servlet CuentaCobroCtrol at " + request.getContextPath() + "</h1>"); 
     out.println("</body>"); 
     out.println("</html>"); 
    } finally { 
     out.close(); 
    } 
} 

private static String getStringFromInputStream(InputStream is) { 

    BufferedReader br = null; 
    StringBuilder sb = new StringBuilder(); 

    String line; 
    try { 

     br = new BufferedReader(new InputStreamReader(is)); 
     while ((line = br.readLine()) != null) { 
      sb.append(line); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (br != null) { 
      try { 
       br.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    return sb.toString(); 

} 


// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
/** 
* Handles the HTTP <code>GET</code> method. 
* 
* @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 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    try { 
     processRequest(request, response); 
    } catch (FileUploadException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (ParseException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (SQLException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

/** 
* Handles the HTTP <code>POST</code> method. 
* 
* @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 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    try { 
     processRequest(request, response); 
    } catch (FileUploadException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (ParseException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (SQLException ex) { 
     Logger.getLogger(CuentaCobroCtrol.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

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

} 
0

Я не уверен, если это поможет любому, как я с помощью аннотаций в этом примере, но вот пример сервлета, который загружает файл и сохраняет его в файловой системе: https://www.openshift.com/forums/openshift/how-to-upload-and-serve-files-using-java-servlets-on-openshift

+0

ммм хорошо здесь дело в том, что я уже сделал файл загрузки сервлета и просто использовали пример для построения этого, моя проблема заключается в чтении входных данных, поступающих из формы, потому что они не подхватываются, а если кажется, что игнорируется после оценки первого. – Leo21

+0

Можете ли вы проверить, что items.size, зарегистрировав его где-нибудь, выведя его на экран? Может быть, просто пропустите его и получите имена полей и распечатайте их? –

+0

Я могу попробовать, но я думаю, что я не получу ничего такого, о чем я упоминал до того, как выполняется первое «если» из списка, в котором оценивается «fechai», но остальное просто нет, и поскольку он выполняет цикл , даже был всего один цикл, я считаю, что он должен выполнить его, потому что цикл был запущен до тех пор, пока использование «для» означает, что цикл выполняется на литах один раз, пока не достигнет условия, поэтому все if должны быть выполнены или Я ошибаюсь? – Leo21

0

Вы получите загруженный файл, если он NOT поле формы. Таким образом, чек должен быть:

if(!item.isFormField()){ 
    String fileName = item.getName(); 
    InputStream is = item.getInputStream(); 
    // process the file 
} else { 
    // Get the field name 
    String fieldName = item.getName(); 
    // Get the field value 
    String value = item.getString(); 
} 

Заканчивать http://commons.apache.org/proper/commons-fileupload/using.html для более подробной информации.

+0

Спасибо, я понимаю, но я хочу получить данные из полей формы, учитывая, что начальная форма представляет собой многостраничную форму, содержащую загружаемый файл и некоторую информацию, что я хочу сделать, это поймать эту информацию из поля формы, чтобы поместить их в переменные, чтобы я мог записать эту информацию в базу данных, загрузить файл, который соответствует этой информации. – Leo21

+0

Тогда почему у вас есть код типа item.getInputStream(), когда это поле формы? Кроме того, все эти файлы? – Salil

+0

'потому что мне нужно получить imput, исходящий из формы, которая равна имени поля, поэтому я использую item.getimputStream для отправки данных в метод преобразования (ObtenerDatoDeFormulario) для этого поля, чтобы он мог быть преобразован в строка! но, как я уже говорил, первое поле формы является единственным, кто признал, что другие просто игнорируются. Я не знаю, почему! – Leo21

Смежные вопросы