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

时间:2022-10-22 20:28:05

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文件上传方法上传文件。对于文件的后端处理我在春天制作了一个控制器。但我无法找到在这种情况下如何处理弹簧2.5中的文件?我的代码是 -

JSP FILE

<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>

1 个解决方案

#1


4  

There are two main steps:

主要有两个步骤:

1) add an instance of multipart resolver to the Spring context

1)将一个多部分解析器的实例添加到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.File from org.springframework.web.multipart.MultipartFile:

要从org.springframework.web.multipart.MultipartFile获取java.io.File的实例:

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

#1


4  

There are two main steps:

主要有两个步骤:

1) add an instance of multipart resolver to the Spring context

1)将一个多部分解析器的实例添加到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.File from org.springframework.web.multipart.MultipartFile:

要从org.springframework.web.multipart.MultipartFile获取java.io.File的实例:

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