需求说明:
简单演示ajax提交fromData类型数据。
代码说明:
ajax在传输数据的时候基本格式大都是固定的,只需要修改传输类型即可。下面介绍基本的参数提交。
步骤一:建立html或者jsp页面,引入jquery-3.2.1.min.js(其他版本亦可)。
步骤二:建立文件选择输入框,上传按钮并给其ID赋值。
步骤三:编写jQuery、ajax代码,完成上传到指定controller。
下面是示例代码:
<!DOCTYPE html> <html lang="en"> <head> <script src="jquery-3.2.1.min.js"></script> <script> $(function () { $("#upload").click(function () { $("#imgWait").show(); var formData = new FormData(); formData.append("myfile", document.getElementById("file1").files[]); formData.append("Type", "Image"); console.log(formData); $.ajax({ url: "http://localhost:8080/XX/XX/uploadFile.do", type: "POST", data: formData, contentType: false, processData: false, success: function (data) { console.log("); }, error: function () { console.log("上传失败!"); } }); }); }); </script> </head> <body> 选择文件:<input type="file" id="file1" /><br /> <input type="button" id="upload" value="上传" /> </body> </html>
总结:上面代码中ajax访问接口实现文件的上传功能,涉及到ajax跨越的问题这里就不做介绍了。