Java 如何使用ajax文件上传和spring mvc上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31832169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:39:25  来源:igfitidea点击:

How to upload file using ajax file upload and spring mvc?

javaajaxspringjspspring-mvc

提问by Amit Das

I have a jsp file in which i am uploading a file using ajax file upload method. For backend handling of file i made a contoller in spring. But i could not find that how can i handle file in spring 2.5 in this condition ? My Code is -

我有一个 jsp 文件,我在其中使用 ajax 文件上传方法上传文件。对于文件的后端处理,我在春季制作了一个控制器。但是我找不到在这种情况下如何在 spring 2.5 中处理文件?我的代码是 -

JSP FILE

JSP文件

<input type="file" name="file" />
<script type="text/javascript">
        function saveMedia() {
            var formData = new FormData();
            formData.append('file', $('input[type=file]')[0].files[0]);
            console.log("form data " + formData);
            $.ajax({
                url : 'ajaxSaveMedia.do',
                data : formData,
                processData : false,
                contentType : false,
                type : 'POST',
                success : function(data) {
                    alert(data);
                },
                error : function(err) {
                    alert(err);
                }
            });
        }
    </script>

采纳答案by Constantine

There are two main steps:

主要有两个步骤:

1) add an instance of multipart resolverto the Spring context

1) 将multipart 解析器的实例添加到 Spring 上下文中

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

2) add a handler method

2) 添加处理程序方法

// I assume that your controller is annotated with /ajaxSaveMedia.do
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String doUpload(@RequestParam("file") MultipartFile multipartFile) {                 
    return "Uploaded: " + multipartFile.getSize() + " bytes";
}


To get an instance of java.io.Filefrom org.springframework.web.multipart.MultipartFile:

要获取java.io.Filefrom的实例org.springframework.web.multipart.MultipartFile

File file = new File("my-file.txt");
multipartFile.transferTo(file);