jinal shah
jinal shah

Reputation: 11

How to get full path of file to read it & save its data in database?

I am trying to read an Excel file & upload its data to database using Spring4 + POI.

Flow for this functionality is:

  1. JSP (select excel file)
  2. Get that file on controller (with complete path)
  3. Pass to service for extracting data.

Problem :: I am getting only file name on controller but I need complete path of that file.

Eg: I get Book.xls in controller but I want D:\Book.xls in controller to read its data.

I need to pass this fullpath to -->

FileInputStream file = new FileInputStream(new File("D:\\Book.xls"));

Because of "Book.xls" it gives me Exception: Exception :Book.xls (The system cannot find the file specified)

JSP code:

<form ... enctype="multipart/form-data">
<input name="file" type="file" />

can you please help me to get path of selected file.

Upvotes: 0

Views: 5493

Answers (1)

Shantaram Tupe
Shantaram Tupe

Reputation: 1666

For security reasons it is not allowed to to upload file with its full path ( client directory structure )

Rather what you can do is,

  1. Upload file ( you have that, already uplaoded)
  2. Store it in server side location
  3. Read it from there

If required I will give code for that, but first try this

You can use apache commons-io's copyFile api for that..

thanks

Update :- My working Code

    for (MultipartFile multipartFile : files) {
        System.out.println(multipartFile.getOriginalFilename()+"       "+multipartFile.getContentType()+" "+multipartFile.getName());
        try {
                multipartFile.transferTo(new File(filePathToSave+"/"+multipartFile.getOriginalFilename()));
        } catch (IllegalStateException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }

Here 'filePathToSave' is path where u want to save file, again read from same path

Upvotes: 2

Related Questions