使用 Thymeleaf 将文件上传到 @ModelAttribute [英] Upload files to the @ModelAttribute using Thymeleaf

查看:26
本文介绍了使用 Thymeleaf 将文件上传到 @ModelAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Thymeleaf 将文件上传到@ModelAttribute?我正在做的事情:

How to upload files to the @ModelAttribute using Thymeleaf? I'am doing something that:

上传.html

<form method="POST" action="#" th:action="@{/sending}" th:object="${collage}" enctype="multipart/form-data" >
            <input type="file" th:field="*{picture}" />
            <input type="file" th:field="*{picture}"  />
            <input type="submit" value="upload" />
</form>

我的控制器:

@Controller
public class MainController {

@GetMapping(value = { "/" })
public String index(){
    return "upload";
}

@GetMapping("/collage")
public String paintPicture(Model model){        
    return "collage";
}

@PostMapping("/sending")
public String redirect(@ModelAttribute(value="collage") Collage collage, RedirectAttributes redirectAttr) {

        Collections.shuffle(Arrays.asList(collage.getCollage()));
        redirectAttr.addFlashAttribute("pictures",collage.getCollage());
        return "redirect:/collage"; 
}
}

拼贴类:

public class Collage {

private MultipartFile[] pictures;

public Collage(){}

public MultipartFile[] getCollage() {
    return pictures;
}

public void setCollage(MultipartFile[] pictures) {
    this.pictures = pictures;
}
}

我得到:java.lang.IllegalStateException: BindingResult 或 bean 名称collage"的普通目标对象都不是请求属性 在控制台和/"页面上的文本:

I'm getting: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'collage' available as request attribute in the console and a text on "/" page:

推荐答案

您可以应用此更改

1) 将@ModelAttibute 改为@RequestParam

1) change @ModelAttibute to @RequestParam

2) 使用 MultipartFile[] 作为参数并且只使用单个输入文件 html

2) use MultipartFile[] as param and only use a single input file html

//name of input html should be collage
@PostMapping("/sending")
public String redirect(@RequestParam("collage") MultipartFile[] files, RedirectAttributes redirectAttr) {

        Collections.shuffle(Arrays.asList(files));
        redirectAttr.addFlashAttribute("pictures",files);
        return "redirect:/collage"; 
}

和你的 html 页面

and your html page

<form method="POST" th:action="@{/sending}" enctype="multipart/form-data" >
            <input type="file" name="collage" multiple="multiple"/>
            <input type="submit" value="upload" />
</form>

这篇关于使用 Thymeleaf 将文件上传到 @ModelAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆