复制下面代码,直接运行即可。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/vue-router/3.0.1/vue-router.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.bootcss.com/element-ui/2.4.0/index.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<link href="/static/css/theme-green/index.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/decoupled-document/ckeditor.js"></script>
<script src="https://unpkg.com/better-scroll/dist/bscroll.min.js"></script>
</head>
<body>
<input type="file" name="" id="fileId" onchange="changeFn()">
<script>
function changeFn() {
let fileDOM = document.getElementById("fileId");
// console.log(fileDOM);
// console.log(fileDOM.files);
// console.log(fileDOM.files[0]);
let formdata = new FormData();
// console.log(formdata);
formdata.append('file', fileDOM.files[0]);
// console.log(formdata);
//获取请求头
axios.get("https://******/api/private/v1/login", {
params: {
username: "******",
password:"******"
}
})
.then(res => {
// console.log(res.data.data.token);
sessionStorage.token = res.data.data.token
})
// // ajax 发送请求
// let xhr = new XMLHttpRequest();
// xhr.open('post', "https://l******/api/private/v1/upload", false);
// xhr.setRequestHeader('Authorization',
// 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2NjMyNTY0NjUsImV4cCI6MTY2MzM0Mjg2NX0.fBtTBySZEa4BxyeSfSsiLNux2XpccCzBBhZpA54uLFY'
// );
// xhr.onreadystatechange = function() {
// if (xhr.readyState == 4) {
// // console.log(xhr.responseText);
// console.log(JSON.parse(xhr.responseText));
// }
// };
// xhr.send(formdata)
// axios 发送formdata文件,作为参数放在data对象中
axios({
url: 'https://******/api/private/v1/upload',
method: 'post',
headers: {
'Authorization': sessionStorage.token
},
data: formdata
})
.then(res => {
console.log(res);
})
}
</script>
</body>
</html>