可以使用FormData 对象和type 属性为 file 的input 元素向服务器发送文件。当表单提交时,FormData对象会自动确保用户选择的文件内容与其他的表单值一同上传。下面的例子展示了如何以这种方式使用FormData对象。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用FormData对象发送文件到服务器</title> <style> .row{display: table-row;} .cell{display: table-cell;padding: 5px;} .lable{text-align: right;} </style> </head> <body> <form method="post" action="http://localhost:53396/ajax/html5/fruitcalc.aspx"> <div> <div> <div>Apples:</div> <div><input value="5" /></div> </div> <div> <div>Bananas:</div> <div><input value="2" /></div> </div> <div> <div>Cherries:</div> <div><input value="20" /></div> </div> <div> <div>File:</div> <div><input type="file" /></div> </div> <div> <div>Total:</div> <div>0 items</div> </div> </div> <button type="submit">Submit Form</button> </form> <script> document.getElementById("submit").onclick = handleButtonPress; var httpRequest; function handleButtonPress(e){ e.preventDefault(); var form = document.getElementById("fruitform"); var formData = new FormData(form); httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = handleResponse; httpRequest.open("POST",form.action); httpRequest.send(formData); } function handleResponse(){ if(httpRequest.readyState == 4 && httpRequest.status == 200){ document.getElementById("results").innerHTML = httpRequest.responseText; } } </script> </body> </html>
此例里,最明显的变化发生在 form元素上。添加了input元素后,FormData对象就会上传用户所选的任意文件。
修改 fruitcalc.aspx 的cs文件如下:
using System; using System.Web; namespace Web4Luka.Web.ajax.html5 { public partial class fruitcalc : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int total = 0; if (Request.HttpMethod == "POST") { if (Request.ContentType.IndexOf("multipart/form-data") > -1) { for (int i = 0; i < Request.Form.Count; i++) { total += Int32.Parse(Request.Form[i]); } if (Request.Files["file"] != null) { HttpPostedFile file = Request.Files["file"]; file.SaveAs(Server.MapPath("/upload/pictures/" + file.FileName)); } } writeResponse(Response, total); } } private void writeResponse(System.Web.HttpResponse Response, int total) { string strHtml; Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:63342"); strHtml = total + " item ordered"; Response.Write(strHtml); } } }
此例的显示效果如下:
以上所述是小编给大家介绍的Ajax 高级功能之ajax向服务器发送数据,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
您可能感兴趣的文章: