-1
        Part part = request.getPart("file");
        if (part != null){
        String fileName = extractFileName(part);
        String filePath = savePath + File.separator + fileName;
        part.write(savePath + File.separator + fileName);
        String imageName = fileName;
        } else{
            String fileName = "avatar.jpg";
            String filePath = savePath + File.separator + fileName;
            part.write(savePath + File.separator + fileName);
            String imageName = fileName;
        }

After inserting the if else statement into the code, my code at the bottom gotten this error saying: imageName cannot be resolved to a variable and filePath cannot be resolved to a variabl. However, once i comment away my if else statement everything is fine. Can someone tell me where is the error?

        request.setAttribute("Pic", filePath);
        request.setAttribute("PicName", imageName);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

2 Answers2

5

Your "filePath" and "imageName" variables are only visible from within the if or else blocks. Declare these variables before the if/then blocks and then set the variable in the if/then code rather than re-declaring it.

String filePath = "";
String imageName = "";
if (...) {
...
} else {
...
}
request.setAttribute("Pic", filePath);
request.setAttribute("PicName", imageName);

See http://www.java-made-easy.com/variable-scope.html for more information on scopes.

CConard96
  • 874
  • 1
  • 7
  • 18
1

Agreed with @CConrad96. However, there are even more improvements that could be done, for example, the last 3 lines on the if and else are the same. Also, if you will write imageName = fileName why not get rid of one ? Last, the argument on part.write and has the same value as filePath, why not use it ?

String fileName:
Part part = request.getPart("file");
if (part != null){
    fileName = extractFileName(part);
} else{
    fileName = "avatar.jpg";
}

String filePath = savePath + File.separator + fileName;
part.write(filePath);

request.setAttribute("Pic", filePath);
request.setAttribute("PicName", fileName);
UDKOX
  • 738
  • 3
  • 15
  • After adding this seems to work thank alots!!! – James_the_97 May 16 '16 at 01:07
  • Sorry, but this code doesnt seem to work as it gave me this error: java.io.IOException: java.io.FileNotFoundException: D:\Nanyang Polytechnic\FYPJ Project2\FYPJ\WebContent\profile (Access is denied) – James_the_97 May 16 '16 at 02:35
  • Are you having this error in the code I wrote ? I think my code is OK, if your program is not allowed to access some directories, it's not the code's fault, is your fault. Check the file is where you wanted it to be, or maybe move it to a simpler loction, (like *C:/resources/[files_here]*. There is no way for me to know why you don't have access to that directory. – UDKOX May 16 '16 at 12:59