3

I am uploading a file using Spring MultipartFile. I need to store the uploaded file attributes like creation date and modified date. Currently I am using following approach:

File dest = new File(uploadfile.getOriginalFilename());
dest.createNewFile(); 
FileOutputStream fos = new FileOutputStream(dest); 
fos.write(uploadfile.getBytes());
fos.close(); 

Path filee = dest.toPath();

BasicFileAttributes attr = Files.readAttributes(filee, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

where uploadfile is the object of spring boot MultipartFile.

Referred links :

How to convert a multipart file to File?

Get java.nio.file.Path object from java.io.File

Determine file creation date in Java

The issue is that I am getting creation date and modified date as the current date only and probably the reason is that the new file object is resetting these values. How can I get the attributes of the original uploaded file?

  • i think it is hard to get the attributes of the original uploaded file, but you can get these values from other request parameters such as ?creationTime=xx&lastAccessTime=xx – clevertension Aug 13 '18 at 14:25

1 Answers1

1

The file meta data (like your creationTime, lastAccessTime, lastModifiedTime) is not part of the file, but the filesystem. Thus by uploading a file you only get the file and not the additional (meta) data that is managed by the filesystem.

You could add the last modified date to the upload form with the help of the File API (access and creation are not supported), but these can be manipulated by the user and thus you cannot trust them, if that is not a problem for you here an example from: https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified

html:

<!-- inside your form -->
<input type="file" multiple id="fileInput">

javascript:

const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(event) {
  // files is a FileList object (similar to NodeList) 
  const files = event.target.files;

  for (let i = 0; i < files.length; i++) {
    const date = new Date(files[i].lastModified);
    alert(files[i].name + ' has a last modified date of ' + date);
    // TODO add the date as a hidden input to your form
  }
});
Pinkie Swirl
  • 2,375
  • 1
  • 20
  • 25