文件上传
方式一
axios 上传方式
构造表单元素,赋予 id(此处 id="form")
<form id="form">
<input type="file" name="verify" />
</form>
JavaScript 脚本
let formData = new FormData(document.getElementById("form"));
this.$axios.post("https://school.glzhxx.com/wxapp/api/common/jssdk/upload/", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then(function (response) {
console.log(response);
});
文件下载
方式一
function download() {
let form = document.createElement("form");
form.style.display = "none";
form.action = "https://work.weixin.qq.com/wework_admin/commdownload?platform=android&from=wwindex";
form.method = "get";
document.body.appendChild(form);
form.submit();
form.remove();
}
构造一个 form,添加属性,确保他不可见,追加到 body 后,触发 submit() 事件,之后移除。
方式二
XMLHttpRequest 方式,会存在跨域问题
function download() {
let xhr = new XMLHttpRequest();
xhr.open("get", "https://work.weixin.qq.com/wework_admin/commdownload?platform=android&from=wwindex", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.responseType = "blob";
xhr.onload = function() {
if (xhr.getResponseHeader("Content-type") == 'application/octet-stream') {
let url = window.URL.createObjectURL(xhr.response);
let a = document.createElement("a");
a.href = url;
a.style.display = 'none';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
} else {
let reader = new FileReader();
reader.addEventListener('loadend', function(e) {
let data = JSON.parse(e.target.result);
alert('提示', "系统出错,错误信息为:" + data.description
+ ",请将该信息提供给代维人员寻求帮助");
});
reader.readAsText(xhr.response);
}
};
xhr.send();
}
方式三
axios,XMLHttpRequest 方式,会存在跨域问题