console
function ajaxUpload() {
var form = document.forms['myForm'];
var formData = new FormData(form); // 或者使用new FormData();
// 增加文件
//formData.append(name, file, filename);
// 增加二进制对象
var dataArray = [185, 254, 185, 254];
//var arrayBuffer = new ArrayBuffer(89085);// js中arrayBuffer是只读,但是可以通过其视图如Int8Array来修改
var int8ArrayView = new Int8Array(dataArray); // 参数可以是arrayBuffer,Int64Array存在不是4整数倍字节的问题
var blob = new Blob([int8ArrayView], {
type: 'text/plain;charset=utf-8',
endings: 'transparent'
});
formData.append('blob', blob, '文本.txt');
// 增加字符串
formData.append('smartphone', 'iphone 8');
// ajax请求
var xhr = new XMLHttpRequest();
xhr.open(form.method || 'GET', form.action, true);
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
var headers = xhr.getAllResponseHeaders();
var arr = headers.trim().split(/[\r\n]+/);
var headerMap = {};
arr.forEach(function(line) {
var parts = line.split(': ');
var header = parts.shift();
var value = parts.join(': ');
headerMap[header] = value;
});
console.log(headerMap);
}
};
// 上传进度事件
xhr.upload.onprogress = function(e) {
var progressBar = document.querySelector('progress');
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
// 兼容不支持 <progress> 元素的老式浏览器
progressBar.textContent = progressBar.value;
}
};
xhr.onload = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 处理服务器返回的数据
var result = xhr.response;
alert(result.message);
} else {
console.error(xhr.statusText);
}
}
};
xhr.ontimeout = function() {
console.error('请求连接超时!');
};
xhr.onerror = function() {
console.error('请求出错!');
};
xhr.onabort = function() {
console.error('请求被取消!');
};
//xhr.setRequestHeader('Content-Type', form.enctype || 'application/x-www-form-urlencoded');// 如果为multipart/form-data,则必须增加boundary,否则后台报错:the request was rejected because no multipart boundary was found
xhr.setRequestHeader('token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzeXNhZG1pbiIsImlhdCI6MTUzMTgzNzMwMywiZXhwIjoxNTMyNDQyMTAzfQ.00IebD8XdrRATTgnf-DdejVsCWGES12gyuYffnpLyP4ffQPn0U7XhzHdFGRuowsa4qBLHVbuh9IKV8FcpEPsvA');
xhr.withCredentials = true; // 允许携带认证的cookie等信息
xhr.timeout = 60 * 1000;
xhr.responseType = 'json';
xhr.send(formData);
}
<div>
<form name="myForm" method="POST" action="http://127.0.0.1:8082/office-service/email/upload"
enctype="multipart/form-data">
<table>
<tr>
<td>
<label for="name">
名称
</label>
</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>
<label for="attachment">
附件
</label>
</td>
<td>
<input type="file" name="attachment" multiple/>
</td>
</tr>
<tr>
<td>
<button type="button" onclick="ajaxUpload();">
测试
</button>
</td>
</tr>
</table>
</form>
<progress min="0" max="100" value="0">
0% complete
</progress>
</div>