Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read the contents of a file upload in java

I know how to upload a file:

<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>

This is the class for reading the file:

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();
        } 

    }
}

Now how do you link both these together. The user uploads the file onto the server and the server processes it. i.e., it accepts the file and prints it contents. Can I use struts framework for this? I want to upload excel sheet and print the contents to the jsp page. I have the code for reading the excel sheet in java using apache poi. But the path to read the excel file is hard coded. how do you take it from the uploaded file?

This is the file for reading excel sheet:

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();
        }
    }
}

Output:

ID NAME LASTNAME 1.0 Amit Shukla 2.0 Lokesh Gupta
3.0 John Adwards 4.0 Brian Schultz

But how do you stitch the uploaded and the servlet file together. How do you read the uploaded file?

like image 730
coder Avatar asked Jun 28 '15 12:06

coder


2 Answers

You can achieve it by breaking whole process in two steps

1) Upload file

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) After upload pass file location to the method which read file data using apche poi. Use File uploadedFile = new File(filePath); object to get file location.

like image 116
Lalit Chattar Avatar answered Oct 11 '22 03:10

Lalit Chattar


Like many operations in Java, reading a file upload is unneccessarily complex, and difficult to work out from the javadocs. You are already planning to use Apache libraries to read your uploaded file, so I recommend using apache.commons.fileupload to upload your file as well.

This code fragment uploads a CSV file into a string:

...

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");
    }
  }
like image 26
Chris Morgan Avatar answered Oct 11 '22 01:10

Chris Morgan