jquery uses formData to upload attachments to the ssm framework

Table of contents

Introduction

Solution

Configure the Spring file

HTML-form form code

jquery code

Controller backend code


Introduction

When using jquery to upload attachments normally, the data transmitted from data to the backend can only be an object.

The picture is stored in the database and in the bean as a string type, but the backend receives a file type.

In this way, the backend cannot be uploaded. In order to solve this problem, we use  the FormData object to upload the attachment

Solution

Configure the Spring file

If you do not configure this, you will not be able to upload files. You must configure it.

<!--  配置multipartResolver,用于上传文件,使用spring的CommonsMultipartResolver  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

HTML-form form code

enctype = "multipart/form-data" must be added, otherwise the attachment cannot be uploaded

The type attribute of the input to be uploaded should be changed to file to upload the file, and the name attribute should be changed to be different from the bean

<form action="/student/add" method="post" id="addForm" enctype="multipart/form-data">
        姓名:<input type="text" name="name"><br>
        家庭住址:<input type="text" name="bigname"><br>
        出生日期:<input type="text" name="riqi"><br>
        班级:<select name="gradeId">
                <option value="0">请选择</option>
                <option value="1">一年级</option>
                <option value="2">二年级</option>
                <option value="3">三年级</option>
            </select><br>
        年龄:<input type="text" name="age"><br>
        图片:<input type="file" id="tupianURL" name="tupianURL"><br>
        <input type="submit" value="添加">
    </form>

jquery code

Create a FormDate object to upload data to the backend. To specify a form, the data in the form will be obtained

Remember to add processData : false and contentType : false in ajax   , if you don’t add it, you will jump to the page

$("#addForm").submit(function (){
        var formData = new FormData(document.getElementById("addForm"));
        $.ajax({
            url:"/student/add",
            type:"post",
            data:formData,
            dataType:"json",
            processData: false,
            contentType: false,
            success:function (data){
                if (data>=1){
                    alert("添加成功");
                }else {
                    alert("添加失败");
                }
            }
        })
        return false;
    })

Controller backend code

Make sure that the path created in the webapp has this path

    @RequestMapping("/add")
    @ResponseBody
    public String add(Student student,MultipartFile tupianURL,HttpServletRequest request){
        if (tupianURL.getSize()>0) {//判断上没上传文件
            String fileType=tupianURL.getOriginalFilename();
            int index=fileType.lastIndexOf(".");
            fileType=fileType.substring(index);
            String path=request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");
            long filename=System.currentTimeMillis();//获取当前时间时间戳
            File file=new File(path+"\\"+filename+fileType);
            try {
                tupianURL.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            student.setTupian(filename+fileType);
        }
        int count=studentService.addStudent(student);
        String result=JSON.toJSONString(count);
        return result;
    }

After the above work is done, you can use ajax to upload attachments!

Guess you like

Origin blog.csdn.net/zky__sch/article/details/132034654