需求說明:
簡單演示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[0]); 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跨越的問題這里就不做介紹了。