无需重定向上传图像Spring MVC

时间:2016-01-14 21:55:32

标签: java ajax spring spring-mvc

我能够上传文件就好了,我只是想防止重定向。这显然是通过AJAX表单提交完成的,但我仍然最终在控制器中,然后重定向我。

我的控制器:

 @RequestMapping(method=RequestMethod.POST)
    public void handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                //return new ModelAndView("redirect:register");
            } catch (Exception e) {
                //return new ModelAndView("redirect:register");
            }
        } else {
            //return new ModelAndView("redirect:register");
        }
    }

JSP部分:

<script>
$('fileUploadForm').submit(function (e) {
    $.ajax({
        url: '${home}upload',
        data: $('fileUploadForm').serialize(),
        processData: false,
        type: 'POST',
        success: function (data) {
            alert(data);
        }
    });

    e.preventDefault();
});
</script>


<form id ="fileUploadForm" method="POST" action="upload?${_csrf.parameterName}=${_csrf.token}" enctype="multipart/form-data">
    File to upload: <input type="file" name="file">
    Name:
    <input type="text" name="name">
    <input type="submit" value="Upload"> Press here to upload the file!
</form>

1 个答案:

答案 0 :(得分:1)

&lt; p&gt;如果你的控制器不是Restfull,那么你需要向方法指出它是一个restfull调用。&lt; / p&gt; &lt; p&gt;请尝试以下修正。&lt; / p&gt; &LT;预&GT;&LT;代码&GT; @RequestMapping(方法= RequestMethod.POST) @ResponseBody //添加这个 public void handleFileUpload(@RequestParam(&#34; name&#34;)String name,@ RequestParam(&#34; file&#34;)MultipartFile file){} &LT; /代码&GT;&LT; /预&GT;