java web学习笔记:springmvc处理表单(包含多文件)上传

一.了解相关知识。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值