java - Spring MVC 映射方法未使用 POST 调用

标签 java spring spring-mvc

我正在尝试使用 Spring MVC 上传文件。 这是 .jsp 页面中的表单

<form:form method="post" commandName="file"  enctype="multipart/form-data">
    Upload your file please:
    <input type="file" name="file" />
    <input type="submit" value="upload" />
    <form:errors path="file" cssStyle="color: #ff0000;" />
</form:form>

在我的 Controller 中,我有 GET 和 POST 方法:

@RequestMapping(method = RequestMethod.GET)
public String getForm(Model model) {
    File fileModel = new File();
    model.addAttribute("file", fileModel);
    return "file";
}

@RequestMapping(method = RequestMethod.POST)
public String fileUploaded(Model model, @Validated File file, BindingResult result) {
    String returnVal = "successFile";
    logger.info("I am here!!!");
    if (result.hasErrors()) {
        returnVal = "file";
    }else{
        MultipartFile multipartFile = file.getFile();
    }
    return returnVal;
}

验证只是检查文件大小是否为零:

public void validate(Object target, Errors errors) {
    File imageFile = (File)target;
    logger.info("entered validator");
    if(imageFile.getFile().getSize()==0){
        errors.rejectValue("file", "valid.file");
    }
}

方法 GET 工作正常并返回文件 View ,但是 Controller 中的 POST 方法不会被调用。单击上传按钮时没有任何反应。

最佳答案

希望这对您有帮助:

Controller 代码

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadInputFiles(@RequestParam("file1") MultipartFile file,
        @RequestParam("fileName") String fileName,
        @RequestParam("fileType") String fileType){

    System.out.println("Upload File Controller has been called");
}

表单提交:

<form method="POST" action="uploadFile" enctype="multipart/form-data">
    File to upload: <input type="file" name="file"><br /> 
    Name: <input type="text" name="name"><br /> <br /> 
    <input type="submit" value="Upload"> Press here to upload the file!
</form>

关于java - Spring MVC 映射方法未使用 POST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694935/

相关文章:

java - 如何不将 DocumentRoot 写入 XML

java - 如何从 spring-dispatcher-servlet.xml 访问 SessionFactory 到 DAO

java - 使用 BinaryTree 将字符编码为二进制

Java Eclipse,如果包含多行,则在方法之后换行?

java - Java Spring 的 JpaRepository : No property findbyUser found for type User

java - Spring:如何将配置从应用程序传递到库

html - 使用 @Controller 显示 index.html 页面 | Spring Boot

spring-mvc - Spring 3 - 测试 Controller @Autowired Servlet 上下文

java - 对密码编码器的服务层进行封装

java - 我的小程序出了什么问题?