我试图在我的 Spring MVC/jsp 项目中获取文件上传页面,并且文件上传正确。它在日志文件中输出文件名,然后我将文件名添加到 ModelAndView 中,当我尝试在 View (.jsp 文件)中访问它们时,它们似乎不存在......但我添加的另一个对象确实存在......
这是我将文件名添加到 ModelAndView 的 Controller :
@RequestMapping(value = "/uploadFiles.html", method = RequestMethod.POST)
public String save(@ModelAttribute Token token, @ModelAttribute("uploadForm") FileUpload fileUpload, ModelAndView mav)
{
List<MultipartFile> files = fileUpload.getFiles();
List<String> fileNames = new ArrayList<String>();
if(files != null && files.size() > 0)
{
for(MultipartFile file : files)
{
if(!file.isEmpty())
{
fileNames.add(file.getOriginalFilename());
logger.info("Got file with name: " + file.getOriginalFilename());
}
}
logger.info("Total filenames: " + fileNames.size());
}
mav.addObject("files",fileNames);
mav.addObject("token",token);
return "etl/EtlUploadSuccess";
}
日志输出显示它正在工作:
09:51:09,072 INFO [Controller] [http-bio-8080-exec-4] Got file with name: ExcelFileOne.xlsx
09:51:09,085 INFO [Controller] [http-bio-8080-exec-4] Got file with name: ExcelFileTwo.xls
09:51:09,096 INFO [Controller] [http-bio-8080-exec-4] Total filenames: 2
这是成功页面的代码片段,其中应显示文件名:
<p>The following files have been uploaded successfully with the token ${token.name}:</p>
<c:forEach items="${files}" var="file">
${file}<br/>
</c:forEach>
页面显示:
The following files have been uploaded successfully with the token testToken:
就是这样...我很困惑为什么文件名没有显示...
最佳答案
尝试更改方法签名以返回 ModelAndView,如下所示
@RequestMapping(value = "/uploadFiles.html", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute Token token, @ModelAttribute("uploadForm") FileUpload fileUpload)
{
List<MultipartFile> files = fileUpload.getFiles();
List<String> fileNames = new ArrayList<String>();
if(files != null && files.size() > 0)
{
for(MultipartFile file : files)
{
if(!file.isEmpty())
{
fileNames.add(file.getOriginalFilename());
logger.info("Got file with name: " + file.getOriginalFilename());
}
}
logger.info("Total filenames: " + fileNames.size());
}
ModelAndView mav = new ModelAndView("etl/EtlUploadSuccess");
mav.addObject("files",fileNames);
mav.addObject("token",token);
return mav;
}
注意我还删除了该方法的 ModelAndView 参数
关于java - 添加到 ModelAndView 的变量似乎消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17926284/