ajax上傳圖片到後臺【formData】
阿新 • • 發佈:2019-02-11
在平時的專案中,我們會遇到各種各樣的上傳圖片,大多數情況下我們會選擇各種各樣的外掛進行上傳,然後返回一個圖片url,在進行相關其他業務
如果不用各種外掛,運用ajax實現頁面上傳圖片也是可以的,這裡用到了formData
首先看一下formData的基本用法:FormData物件,可以把所有表單元素的name與value組成一個queryString,提交到後臺。只需要把 form 表單作為引數傳入 FormData 建構函式即可:
var form = document.getElementById("uploadPicForm"); var formData = new FormData(form);
這樣就可以把formData作為引數直接通過呼叫ajax進行圖片上傳和表提交
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/js/jquery-1.11.1.min.js"></script> <title>表單裡上傳圖片</title> </head> <body> <div> <form action="${pageContext.request.contextPath}/do/uploadControl/saveInfo" method="post" id="uploadPicForm" name="uploadPicForm" enctype="multipart/form-data"> <input id="id" name="id" value="這是id"/> <br> <input id="age" name="age" value="這是age"/> <br> <input type="file" name="uploadFile" id="uploadFile" onChange="uploadPicForm.url.value=this.value" /> <input type="text" id="url" name="url" /> <input type="button" id="it" value="上傳" style="height:29px;margin-left: -5px;" onclick="doUpload()" /> <br> <input type="submit" value="提交" /> </form> </div> </body> <script type="text/javascript"> var ctx = "${pageContext.request.contextPath}"; function doUpload(){ var form = document.getElementById("uploadPicForm"); var formData = new FormData(form) $.ajax({ url: ctx+'/do/uploadControl/uploadPic' , type: 'POST', data: formData, dataType: "json", async: false, cache: false, contentType: false, processData: false, success: function (returndata) { if(returndata.success){ $("#url").val(returndata.data); alert('成功'); return; } }, error: function (returndata) { alert(returndata.msg); //alert("上傳失敗"); } }); } </script> </html>