axios 发送application/x-www-url-encoded、axios上传文件、axios下载文件、 ajax下载文件

axios常见用法

工作中,经常用到axios,axios 发送application/x-www-url-encoded,axios上传文件,axios下载文件或者ajax下载文件,这里做个总结。

axios 发送application/x-www-url-encoded

默认的axios以json格式发送数据,如果想发送application/x-www-url-encoded,则使用qs将数据编码一下再发送,

const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

axios上传文件

axios上传文件,使用FormData,FormData既可以上传文件也可以传文本,如果发送的数据不是File也不是Blob,则会转为字符串。

const form = new FormData();
form.append('my_field', 'my value');
form.append('my_file', fileInputElement.files[0]);
axios.post('https://example.com', form, { headers: form.getHeaders() })

FormData的常见用法如下

const formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like object
const content = '<q id="a"><span id="b">hey!</span></q>'; // the body of the new file…
const blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
const request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);

ajax下载文件、axios下载文件

下载文件,通常采用非ajax下载文件,比如点击一个超链接、点击一个按钮,而在前端分离的项目中,用户登录标识通常在header中,为了携带登录凭证,就有了ajax下载文件的需求。浏览器对Blob API 的支持,让ajax下载文件成为可能,这里以axios举例;大体的思路是请求二进制数据,然后将二进制转为URL,创建超链接,超链接的地址就是这个URL,点击后下载,下载完毕后,释放内存。

axios.get(url,{responseType:'blob'}).then(resp=>{
	let _res = res.data;
	const fileName = "自定义文件名称或者从header中content-disposition取也可以";
	let blob = new Blob([_res]);
	let downloadElement = document.createElement('a');
	let href = window.URL.createObjectURL(blob); // 创建下载的链接
	downloadElement.href = href;
	downloadElement.download = `${fileName}`; // 下载后文件名
	document.body.appendChild(downloadElement);
	downloadElement.click(); // 点击下载
	document.body.removeChild(downloadElement); // 下载完成移除元素
	window.URL.revokeObjectURL(href); // 释放掉blob对象
})

个人公众号

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/126836740