一.了解相关知识。

(1)MultipartResolver 处理文件上传
(2)FormData API

二.导入jar包

ssm框架jar包

三.前端代码样例

(1)html代码:

<body>
    <div id="app">
        <form id="myForm" enctype="multipart/form-data">
            <input type="file" name="files" ref="input1"><br/>
            <input type="file" name="files" ref="input2"><br/>
            年龄: <input type="text" name="name"><br/>
            age:<input type="text" name="age"><br/>
            email:<input type="text" name="email"><br/>
            id:<input type="text" name="id"><br/>
            <input type="button" @click="submit" value="提交">
        </form>
    </div>
</body>

(2)JavaScript:

 const app = new Vue({
        el: "#app",
        data: {
        },
        methods:{
            submit:function (e){
                const form = document.getElementById("myForm");

                const formData = new FormData(form);
                console.log(formData.getAll("files")); //该方法与append方法相对应
                $.ajax({
                    url:'',
                    type:"post",
                    data:formData,
                    contentType:false,
                    processData: false,
                    success: function(respond){
                        console.log(respond)
                    },
                    error: function(message){
                    }
                })
            },
        }
    });

注意: contentType和processData都设置为false。enctype设置可有可无。

四.controller代码

@RequestMapping(value = "/upload.do")
@ResponseBody
    public String upload(MultipartFile[] files, HttpServletRequest request, Student student){
        String ans = "hello";
        System.out.println("student: " + student);
        System.out.println("uploading...");
        if(files!=null && files.length > 0){
            for(MultipartFile file: files){
                System.out.println("create file: " + file.getOriginalFilename());
                String path = request.getServletContext().getRealPath("upload");
                System.out.println(path);

                File directory = new File(path);
                if (!directory.exists()){
                    System.out.println("directory not exists");
                    directory.mkdirs();
                }

                String name = file.getOriginalFilename();
                File destFile = new File(path,name);
                try {
                    file.transferTo(destFile);
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                    ans = "error";
                }
            }
        }

        return ans;
    }

注意: MultipartFile数组的名字要与上传文件的标签名一样(这里都为files)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐