<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data"> <h1 >測試經過Rest接口上傳文件 </h1> <p >指定文件名: <input type ="text" name="filename" /></p> <p >上傳文件: <input type ="file" name="file" /></p> <p >關鍵字1: <input type ="text" name="keyword" /></p> <p >關鍵字2: <input type ="text" name="keyword" /></p> <p >關鍵字3: <input type ="text" name="keyword" /></p> <input type ="submit" value="上傳"/> </form>
$.ajax({
url : "http://localhost:8080/STS/rest/user",
type : "POST",
data : $( '#postForm').serialize(),
success : function(data) {
$( '#serverResponse').html(data);
},
error : function(data) {
$( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);
}
});
關於FormData及其用法php
FormData
.利用
FormData對象
,咱們能夠經過JavaScript用一些鍵值對來模擬一系列表單控件,咱們還能夠使用XMLHttpRequest的
send()
方法來異步的提交這個"表單".
FormData
的最大優勢就是咱們能夠異步上傳一個二進制文件.
var oData = new FormData(document.forms.namedItem("fileinfo" )); oData.append( "CustomField", "This is some extra data" ); var oReq = new XMLHttpRequest(); oReq.open( "POST", "stash.php" , true ); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!" ; } else { oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; } }; oReq.send(oData);
<form id= "uploadForm"> <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上傳文件: <input type="file" name="file"/></ p> <input type="button" value="上傳" onclick="doUpload()" /> </form>
function doUpload() { var formData = new FormData($( "#uploadForm" )[0]); $.ajax({ url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' , type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); }