FileNotFoundException (Is a Directory)
This error occured to me because I was using file.mkdirs()
with complete fileName .
Suppose your file path is emulated/0/test/images/img.jpg
Then remove last part from the path and use file.mkdirs()
on result file
File file = new File("emulated/0/test/images/")
if (!file.exists()) {
file.mkdirs();
}
Looks like in some cases filename
is blank or null so File outputPath=new File(uploadDirPath + File.separator + fileName);
will be a directory and here new FileOutputStream(outputPath);
you try to write to a directory not to a file. So you should check if filename
is not blank.
You have many errors in your code. For one, you only close the last InputStream
s and OutputStream
s; you should close each of them. The way you do things here, you have a resource leak.
Second, this is 2015; therefore drop File
and use java.nio.file instead; plus, use try-with-resources.
Third: right now you upload in the project directory; don't do that when the application runs "live" on a server, this obviously won't work.
Sample:
private static final Path BASEDIR = Paths.get("/path/to/upload/directory");
// in the upload method:
Files.createDirectories(BASEDIR);
String fileName;
Path path;
for (final Part part: request.getParts()) {
fileName = getFileName(part);
if (fileName.isEmpty())
continue;
path = BASEDIR.resolve(fileName);
try (
final InputStream in = part.getInputStream();
) {
Files.copy(in, path, StandardOpenOption.CREATE_NEW);
}
}