我正在尝试在我的Spring MVC / jsp项目中获取文件上传页面并且我已正确上传文件..它在日志文件中输出文件名,然后我将文件名添加到ModelAndView和当我尝试在视图(.jsp文件)中访问它们时,它们似乎根本不存在..但我添加的另一个对象是..
这是我将文件名添加到ModelAndView的控制器:
@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:
宣布就是这样......我为什么文件名没有显示而感到困惑......
答案 0 :(得分:1)
尝试更改方法签名以返回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参数移除到方法
答案 1 :(得分:0)
它只在非空时显示,所以文件可能是空的?
if(!file.isEmpty()) {
fileNames.add(file.getOriginalFilename());
logger.info("Got file with name: " + file.getOriginalFilename());
}
只是一个猜测。