标签:http io ar os 使用 sp java for 文件
首先来认识一下FormData表单
var formData = new FormData(); formData.append(‘name‘, ‘zhangsan‘); formData.append(‘age‘, 20); formData.append(‘gender‘, ‘M‘); //防止跨域,注意,该字符串由服务端生成后一部分发送到session中,一部分放在form隐藏域中 formData.append(‘csrf‘, ‘yty98db128swdx827dcd3jdxh‘); 或者使用另一种方式 <form id=‘registerform‘ name=‘user/register‘ action=‘user/register‘> <input type=‘text‘ name=‘username‘ value=‘张三‘> <input type=‘email‘ name=‘email‘ value=‘zhangsan@example.com‘> <input type=‘number‘ name=‘birthDate‘ value=‘1940‘> <input type=‘submit‘ onclick=‘sendForm(this.form); return false;‘> </form> var formData = new FormData(document.forms[‘registerform‘]); formData.append(‘csrf‘, ‘yty98db128swdx827dcd3jdxh‘);
让后构建Ajax
function sendForm(formData) { var xhr = new XMLHttpRequest(); xhr.open(‘POST‘, form.action, true); xhr.onload = function(e) { // ... }; // 指定通信过程中状态改变时的回调函数 xhr.onreadystatechange = function() { // 通信成功时,状态值为4 var completed = 4; if(xhr.readyState === completed) { if(xhr.status === 200) { // 处理服务器发送过来的数据 }else{ // 处理错误 } } }; xhr.send(formData); }
使用FormData进行文件上传
function uploadFiles(url, files) { var formData = new FormData(); for (var i = 0, file; file = files[i]; ++i) { formData.append(file.name, file); } var xhr = new XMLHttpRequest(); xhr.open(‘POST‘, url, true); xhr.onload = function(e) { ... }; xhr.send(formData); // multipart/form-data } document.querySelector(‘input[type="file"]‘).addEventListener(‘change‘, function(e) { uploadFiles(‘/server‘, this.files); }, false);
function upload(blobOrFile) { var xhr = new XMLHttpRequest(); xhr.open(‘POST‘, ‘/server‘, true); xhr.onload = function(e) { ... }; // Listen to the upload progress. var progressBar = document.querySelector(‘progress‘); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { progressBar.value = (e.loaded / e.total) * 100; progressBar.textContent = progressBar.value; // Fallback for unsupported browsers. } }; xhr.send(blobOrFile); } upload(new Blob([‘hello world‘], {type: ‘text/plain‘}));
参考链接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
http://javascript.ruanyifeng.com/bom/ajax.html
http://hushicai.com/2014/03/29/html5-du-qu-ben-di-wen-jian.html
标签:http io ar os 使用 sp java for 文件
原文地址:http://my.oschina.net/ososchina/blog/348734