JQuery Ajax上传文件

使用jQuery封装的Ajax实现单文件上传,后台使用了Java springboot框架接收文件处理,当然其它语言也都差不多,主要是前端代码。

菜鸟笔记,老鸟请绕飞!

1.html代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <input type="file" name="img" id="img" />
        <input type="text" name="name" id="name" />
        <button onclick="submitform()">提交</button>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script language="javascript">
            function submitform(){
                //构造FormData
                var formdata = new FormData();
                formdata.append('img', $("#img")[0].files[0]);  //加上[0]是将jquery对象转为js对象
                formdata.append('name', $("#name").val());
                $.ajax({
                    type: 'post',
                    url: '/upload',
                    data: formdata,
                    processData: false, //formdata已将数据序列化,无需在处理
                    contentType: false, //formdata无需设置请求头
                    success: function(res) {
                        console.log(res);
                    }
                });
            }
        </script>
    </body>
</html>

2.Java代码

@PostMapping("/upload")
@ResponseBody
public String upload(MultipartFile img, String name){
    String imgName = img.getOriginalFilename();
    try {
        img.transferTo(new File("C:/"+imgName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(name);
    return "ok";
}

 - - - - - - - - - - - - - - - - - - - - - - - - - 这是一条美丽的分割线 - - - - - - - - - - - - - - -- - - - - - - - - 

注:

以上html代码中,为了阻止表单提交,所以没有嵌套form标签,如果觉得不够规范可以加上form标签,然后阻止表单的submit跳转事件

修改后的html代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form id="ajaxform" onsubmit="submitform()"enctype="multipart/form-data" method="post">
            <input type="file" name="img" id="img" />
            <input type="text" name="name" id="name" />
            <input type="submit">提交</button>
        </form>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script language="javascript">
            function submitform(){
                event.preventDefault(); //阻止form表单默认提交,或者在方法结尾return
                //构造FormData
                var formdata = new FormData($("#ajaxform")[0]);//直接传入form表单,[0]是将jQuery对象转为javascript对象
                $.ajax({
                    type: 'post',
                    url: '/upload',
                    data: formdata,
                    processData: false, // 不处理数据
                    contentType: false, // 不设置内容类型
                    success: function(res) {
                        console.log(res);
                    }
                });
            }
        </script>
    </body>
</html>
原文地址:https://www.cnblogs.com/dch0/p/11798851.html