vue使用原生js上传图片demo
2020-10-26 本文已影响0人
无疆wj
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.input-img-btn {
display: block;
width: 240px;
height: 30px;
line-height: 30px;
text-align: center;
margin: 10px auto;
border-radius: 2px;
background-color: #26a2ff;
color: #fff;
}
.upload-img-list {
display: flex;
flex-wrap: wrap;
}
.upload-img-list li {
margin-bottom: 10px;
width: 20%;
position: relative;
list-style: none;
}
.upload-img-list li img {
display: block;
width: 80%;
margin: 0 auto;
}
.upload-img-list li .upload-close {
position: absolute;
top: 0;
right: 0;
color: #fff;
font-weight: 700;
background-color: red;
border-radius: 50%;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
}
</style>
</head>
<body>
<div id="app">
<div class="upload-img-component">
<div>
<label class="input-img-btn" for="file_input">选择图片</label>
<input id="file_input" style="display:none;" type="file" accept="image/*"
@change="inputFile" />
<!-- 上传列表 -->
<ul class="upload-img-list">
<li v-for="(item, index) in fileList" :key="index">
<img :src="item.base64" alt />
<div class="upload-close" @click="closeImg(index)">X</div>
</li>
</ul>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
fileList: [],
formData: null
},
methods: {
// 选择图片
inputFile(e) {
console.log(e)
let files = e.target.files
let fileList = this.fileList // 存储图片数据
let formData = new FormData() // formData对象
for (let i = 0; i < files.length; i++) {
if (!files[i].type.match(/.jpg|.png|.jpeg/i)) {
alert("图片格式错误,请上传png/jpg/jpeg格式的图片!")
return
}
formData.append("file" + i, files[i]) //添加Fail类型的图片信息的参数
this.submit(formData); // 上传
let reader = new FileReader()
// reader.readAsArrayBuffer(files[i]) // 将file读取为ArrayBuffer,存在reader.result里
reader.readAsDataURL(files[i]) // 将file读取为base64,并存在reader.result里
reader.fileName = files[i].name
reader.onload = function () {
console.log(this)
let imgMsg = {
name: this.fileName, //获取文件名
base64: this.result, //base64或ArrayBuffer类型的数据
}
fileList.push(imgMsg)
}
}
},
// 删除图片
closeImg(index) {
this.fileList.splice(index, 1)
},
// 提交数据
submit(formData) {
let config = {
headers: { 'Content-Type': 'multipart/form-data' }
}; //添加请求头
axios.post('/xapi/upimage', formData, config).then(response => {
console.log(response.data);
})
},
},
})
</script>
</body>
</html>