-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;
        }

在代码中插入 if else 语句后,我在底部的代码收到此错误消息:无法将 imageName 解析为变量,并且无法将 filePath 解析为变量。但是,一旦我注释掉我的 if else 语句,一切都很好。有人可以告诉我错误在哪里吗?

        request.setAttribute("Pic", filePath);
        request.setAttribute("PicName", imageName);
4

2 回答 2

5

您的“filePath”和“imageName”变量仅在 if 或 else 块中可见。在 if/then 块之前声明这些变量,然后在 if/then 代码中设置变量,而不是重新声明它。

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

有关范围的更多信息,请参见http://www.java-made-easy.com/variable-scope.html

于 2016-05-15T02:24:10.853 回答
1

同意@CConrad96。然而,还有更多可以做的改进,例如,ifand的最后 3 行else是相同的。另外,如果你会写,imageName = fileName为什么不去掉一个?最后,参数 onpart.write和 具有相同的值filePath,为什么不使用它呢?

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);
于 2016-05-15T02:45:35.830 回答