web-dev-qa-db-fra.com

lire le contenu d'un fichier téléchargé en java

Je sais comment télécharger un fichier:

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>

<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">

File :<input type="file" name="file" size="50" />

<input type="submit" value="Upload File"/>


</form>
</body>
</html>

C'est la classe pour lire le fichier:

import Java.io.BufferedReader;
import Java.io.FileReader;
import Java.io.IOException;

public class BufferedReaderExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
        {

            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}

Maintenant, comment reliez-vous ces deux éléments? L'utilisateur télécharge le fichier sur le serveur et le serveur le traite. c'est-à-dire qu'il accepte le fichier et imprime son contenu. Puis-je utiliser struts framework pour cela? Je veux télécharger une feuille Excel et imprimer le contenu sur la page jsp. J'ai le code pour lire la feuille Excel en Java avec Apache Poi. Mais le chemin pour lire le fichier Excel est codé en dur. comment prenez-vous le fichier téléchargé?

Ceci est le fichier pour lire la feuille Excel:

public class ReadExcelDemo
{
    public static void main(String[] args)
    {
        try
        {
            FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType())
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Sortie:

NOM D'IDENTIFICATION 1.0 Amit Shukla 2.0 Lokesh Gupta
3.0 John Adwards 4.0 Brian Schultz

Mais comment assembler le fichier téléchargé et le fichier de servlet. Comment lisez-vous le fichier téléchargé?

6
coder

J? ai compris. Le fichier d'index (html) sert à télécharger le fichier (comme ci-dessus dans mon qquestion) La classe Java pour cela est:

import Java.io.*;
import Java.util.*;

import javax.servlet.ServletConfig;
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.FileUploadException;
import org.Apache.commons.fileupload.disk.DiskFileItemFactory;
import org.Apache.commons.fileupload.servlet.ServletFileUpload;
import org.Apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, Java.io.IOException {
      // Check that we have a file upload request


      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      Java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>"); 
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{ 
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);

      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      String fileName = "";
      while ( i.hasNext () ) 
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )  
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
             fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath + 
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath + 
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
            out.println("Uploaded in location: "+filePath);
         }
      }
      out.println("</body>");
      out.println("</html>");
      ReadExcelDemo rd = new ReadExcelDemo();
      System.out.println("file name: "+fileName.substring(fileName.lastIndexOf("\\")));
      String s = fileName.substring(fileName.lastIndexOf("\\"));
      System.out.println(filePath);
      System.out.println(s);
      String fileP = filePath.concat(s+"\\");

      System.out.println(fileP);
      rd.read(fileP);

   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, Java.io.IOException {

        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}

C’est la classe pour lire la feuille Excel à l’aide des jarres Apache:

import Java.io.File;
import Java.io.FileInputStream;
import Java.io.FileOutputStream;
import Java.util.Iterator;

import org.Apache.poi.ss.usermodel.Cell;
import org.Apache.poi.ss.usermodel.Row;
import org.Apache.poi.xssf.usermodel.XSSFSheet;
import org.Apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelDemo { 
    public static void read(String filePath)  {
//  public static void main(String[] args){
 try {           
     FileInputStream file = new FileInputStream(new File(filePath));  
//   FileInputStream file = new FileInputStream(new File("C:\\work\\demo.xlsx"));
    //Create Workbook instance holding reference to .xlsx file  
    XSSFWorkbook workbook = new XSSFWorkbook(file); 
    //Get first/desired sheet from the workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    //Iterate through each rows one by one  
    Iterator<Row> rowIterator = sheet.iterator();   
    while (rowIterator.hasNext()) {            
        Row row = rowIterator.next();
        //For each row, iterate through all the columns  
        Iterator<Cell> cellIterator = row.cellIterator();   
        while (cellIterator.hasNext())  {               
            Cell cell = cellIterator.next();    
            //Check the cell type and format accordingly   
            switch (cell.getCellType())                     {        
                case Cell.CELL_TYPE_NUMERIC:  System.out.print(cell.getNumericCellValue() + "\t"); 
            break;                       
                case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t");  
            break;     
            }           
        }             
        System.out.println("");         
    }  
/*  int row=0;
    int k=1;
    Row myRow = sheet.createRow ((short)row);
     myRow.createCell(k).setCellValue ("new data"); 
      myRow = sheet.createRow ((short)row++); */
//  Cell cell1 = sheet.   // Access the second cell in second row to update the value

  //  cell1.setCellValue("OverRide Last Name");

     Cell cell1 = null; // declare a Cell object

     cell1 = sheet.getRow(2).getCell(2);   // Access the second cell in second row to update the value

     cell1.setCellValue("OverRide Last Name");


    file.close();
/*  FileOutputStream out = new FileOutputStream(new File("write_demo1.xlsx"));
    workbook.write(out);  
    out.close(); */
    }
    catch (Exception e) {      
        e.printStackTrace();   
        }
    }
 }
0
coder

Vous pouvez y arriver en cassant tout le processus en deux étapes

1) Télécharger le fichier

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // Java
        factory.setRepository(new File(System.getProperty("Java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

2) Après le téléchargement, passez l’emplacement du fichier à la méthode qui lit les données du fichier à l’aide de apche poi. Utilisez l'objet File uploadedFile = new File(filePath); pour obtenir l'emplacement du fichier.

3
Lalit Chattar

Comme beaucoup d’opérations en Java, la lecture d’un fichier téléchargé est extrêmement complexe et difficile à maîtriser à partir des javadocs. Vous envisagez déjà d’utiliser les bibliothèques Apache pour lire votre fichier téléchargé. Je vous recommande donc d’utiliser Apache.commons. fileupload pour télécharger votre fichier aussi.

Ce fragment de code télécharge un fichier CSV dans une chaîne:

...

import org.Apache.commons.fileupload.*;
import org.Apache.commons.fileupload.disk.*; 
import org.Apache.commons.fileupload.servlet.*;

...

  if (ServletFileUpload.isMultipartContent(request)) {
    int i=0;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // files smaller than 5MB will be held in memory
    factory.setSizeThreshold(5000000); 

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(10000000); // max size of attachment 10MB

    List list = upload.parseRequest(request);
    Iterator iter = list.iterator();

    String csv = null;

    while (iter.hasNext()) {            
      FileItem param = (FileItem)iter.next();
      if (!param.isFormField()) { 
        csv = param.getString();
        break;
      }
    }

    if (csv==null) {
      throw new Exception("CSV buffer not uploaded");
    }
  }
2
Chris Morgan