jquery - Spring 3.0中通过Ajax上传文件

标签 jquery ajax spring file file-upload

在 Spring 3.0 中通过 Ajax 上传文件的最佳或最简单方法是什么?
我想通过 Ajax 提交一个包含文件的表单。此外,解决方案不应依赖于 Flash 等,如 Uploadify 。我试过Jquery form plugin但无法使其工作。您可以查看我的 previous question更多细节。

谢谢!

<小时/>

编辑:我想通过 Ajax 提交包含文件的表单。在服务器端,我想将其收集在模型属性中。

最佳答案

我最近使用 Dojo Iframe 完成了此操作。这是代码(需要从表单标记的 action="return SubmitForm();"调用它):

submitForm = function() {
dojo.io.iframe.send({
    url : "/uploadForm",
    form : "html_form_id",
    method : "POST",
    handleAs : 'text',
    load : function(response, ioArgs) {
            //handle your response here...
            return response;
    },
    error : function(response, ioArgs) {
        if (ioArgs.xhr.status != 0) {
            try {
                //handle error here
            } catch (e5) {
            }
        }
        return response;
    }
});
return false;
}

在服务器端,在 Spring Controller 中,您可以将其处理为:

    @RequestMapping(method = RequestMethod.POST, value = "/uploadForm")
    public ModelAndView onSubmit(
            @RequestParam("file") MultipartFile multipartFile,
        final HttpServletResponse response)
        throws Exception 
    { 

        String fileName="";
        if(multipartFile!=null)
        {
                    fileName = multipartFile.getOriginalFilename();
        }

        //file inputstream can be accessed as multipartFile.getInputStream()

        String resultCode = "0";

        final String responseHTML = "<html><head></head><body><textarea>" + resultCode + "</textarea></body></html>";
        response.setContentType("text/html");

        final OutputStream responseStream = response.getOutputStream();
        responseStream.write(responseHTML.getBytes());
        responseStream.write("\r\n".getBytes());
        responseStream.close();
    }

您需要将文件类型输入参数命名为“file”(如处理函数所示@RequestParam(“file”))

关于jquery - Spring 3.0中通过Ajax上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8999257/

相关文章:

javascript - 如何创建动画实时排行榜?

javascript - 提交问题内部服务器错误

jquery - Bx slider - 使用全宽轮播时在最右侧显示部分幻灯片

javascript - 没有实现接口(interface)元素

java - @CacheEvict 注释是否适用于私有(private)方法?

java - CustomRepositoryImpl 中的 Autowiring bean 为 null

java - Spring Boot - 从 application.yml 注入(inject) map

javascript - 在使用 jQuery 拖动时向元素添加 CSS 类

javascript - jQuery getJSON 不发送 cookie

使用 setInterval 的 JavaScript 内存泄漏