0

I have the following method, with the simple aim to store the contents of a given MultipartFile instance under a specified directory:

private void saveOnDisk(final String clientProductId, final MultipartFile image, final String parentDirectoryPath, final String fileSeparator) throws IOException
    {
        final File imageFile = new File(parentDirectoryPath + fileSeparator + clientProductId + image.getOriginalFilename());
        image.transferTo(imageFile);
        OutputStream out = new FileOutputStream(imageFile);
        out. //... ? How do we proceed? OutputStream::write() requires a byte array or int as parameter
    }

For what it might be worth, the MultipartFile instance is going to contain an image file which I receive on a REST API I'm building.

I've checked some SO posts such as this and this but this problem is not quite touched: I'm effectively looking to create an entirely new image file and store it on a specified location on disk: the method write() of OutputStream, given that it requires byte[] or int params, doesn't seem to be fitting my use case. Any ideas?

Jason
  • 2,495
  • 4
  • 26
  • 37
  • From which library is `MultipartFile` from? Is it `org.springframework.web.multipart.MultipartFile`? Calling `transferTo(...)` might already be enough to store the file. The constructor `FileOutputStream(File)` is not very clear regarding this, but it actually truncates the existing file, which is likely why you are thinking that it did not work. Therefore just omit the creation of the `FileOutputStream`. – Marcono1234 Dec 18 '20 at 21:09
  • Yes, it is that class' instance. So just creating the `File` instance and doing a `transferTo()` towards it from my `MultipartFile` instance also flushes the elements to disk? I will try this in a toy project. – Jason Dec 18 '20 at 21:32
  • And you really **should not include `image.getOriginalFilename()` in the file name**. The multipart file name is client controlled and despite browsers normally not sending directory names an attacker can easily provide an arbitrary name ([cURL examples](https://superuser.com/a/149335)). See also [OWASP File Upload Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html#filename-sanitization) and [Unrestricted File Upload Vulnerability](https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload). – Marcono1234 Dec 18 '20 at 21:37
  • And there was no way I could know that without this information. Very appreciated. – Jason Dec 18 '20 at 22:06
  • Did using only `transferTo(...)` work? If so I will write up these comments as answer then. – Marcono1234 Dec 18 '20 at 23:58
  • Unfortunately, so far it has *not* worked. I am not seeing a file dumped on disk. – Jason Dec 21 '20 at 23:08

0 Answers0