【问题标题】:Upload image without redirection Spring MVC上传图片而不重定向 Spring MVC
【发布时间】:2016-04-20 10:11:10
【问题描述】:

我可以上传文件就好了,我只是想防止重定向。这显然是通过 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>

【问题讨论】:

    标签: java ajax spring spring-mvc


    【解决方案1】:

    如果您的控制器不是 Restfull,那么您需要向该方法表明它是一个 restfull 调用。

    尝试以下修复。

    @RequestMapping(method=RequestMethod.POST)
    @ResponseBody // add this
    public void handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {}
    

    【讨论】:

    • 我明白你的意思,我试过了,我确信它会起作用,但它没有。还有其他建议吗?
    • 那么重定向实际上是做什么的,它会把你带到完全不同的页面还是只是刷新同一个页面?
    • 它带我到另一个页面。到/上传。
    • 当您被重定向时,/upload URi 是否在其末尾也包含 CSRF?你的文件也被上传了吗?
    • 你的两个问题的答案都是肯定的。
    猜你喜欢
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2012-12-02
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多