Path Manipulation error fix for filename

Alpesh003 picture Alpesh003 · May 7, 2015 · Viewed 8.1k times · Source

I have a piece of code where-in I have to read a file for its possible contents.

I'm encountering Path Manipulation Error for the same.

PFB the code:

while ((ze = zis.getNextEntry()) != null) {
    String fileName = ze.getName();
    String esapiFileName = ESAPI.encoder().canonicalize(fileName);
    boolean esapiValidFileName = ESAPI.validator().isValidFileName("upload", esapiFileName, false);
    String _completefileNamePath = null;
    if (esapiValidFileName) {
      _completefileNamePath = _destination + esapiFileName;
      // Below line having Path Manipulation error
      FileOutputStream fos = new FileOutputStream(new File(_completefileNamePath).getCanonicalFile());
      // Path Manipulation error ends
      while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
        fos.write(buffer, 0, size);
      }// while
      fos.flush();
      fos.close();
      zis.closeEntry();
    }
}

Answer

Daniel Sperry picture Daniel Sperry · May 7, 2015

Are your paths relative or absolute?

BTW, You actually don't need to get the canonical file before opening a FileOutputStream:

FileOutputStream fos = new FileOutputStream(_completefileNamePath);

or

FileOutputStream fos = new FileOutputStream(new File(_completefileNamePath));

or

import java.nio.file.Files;
import java.nio.file.Paths;

while ((ze = zis.getNextEntry()) != null) {
    String fileName = ze.getName();
    String esapiFileName = ESAPI.encoder().canonicalize(fileName);
    boolean esapiValidFileName = ESAPI.validator().isValidFileName("upload", esapiFileName, false);
    String _completefileNamePath = null;
    if (esapiValidFileName) {
        _completefileNamePath = _destination + esapiFileName;
        // optional: Files.createDirectories(Paths.get(_completefileNamePath).getParent());
        Files.copy(zis, Paths.get(_completefileNamePath));
        zis.closeEntry();
    }
}