为什么此java post方法控制器未收到此发布表格?

时间:2018-10-21 08:37:30

标签: java spring spring-mvc html-form html-form-post

这是表格:

<form method="post"  enctype="multipart/form-data" id="uploadFileForm" action="/uploadTest">
     <div>
        <input type="file" id="image_uploads" name="filename" accept=".jpg, .jpeg, .png, .pdf" multiple>
    </div>
    <div id="uploadpreview">
        <p>No files currently selected for upload</p>
    </div>
    <div>
        <button id="uploadBtn" type="submit">Submit</button>
    </div>
</form>

这是控制器:

@Controller
@RequestMapping(value = "/**/uploadTest")
public class UserFileUploadController {

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String TestRun(@ModelAttribute("filename") final File uploadFile)
    {
    //code in which i use the uploaded file
        return ("redirect:/solutions");
    }
}

我收到“ 405方法不允许”状态码=屏幕显示“服务器错误”。 但是页面刷新到/ uploadTest,所以我不知道控制器出了什么问题。

1 个答案:

答案 0 :(得分:0)

我认为您应该将File替换为MultipartFile,然后如果要在文件系统中存储文件,请调用transferTo方法。

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String TestRun(@ModelAttribute("filename") final MultipartFile uploadFile) throws IOException {
    File file = ...
    uploadFile.transferTo(file);
    return ("redirect:/solutions");
}

还应该检查是否在dispatcher-servler.xml中定义了该bean,并将maxUploadSize设置为正确的值。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1000000" />
</bean>