JavaScript 文件下载或上传的实现方式

文件上传

方式一

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 方式,会存在跨域问题

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罐装面包

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值