沒有用插件就簡單的圖片上傳
頁面布局如下
<div class="input-up">
<input
type="file"
accept="image/*"
style="display:none"
@change="changeImg()"
name="upload_file"
ref="input"
/>
<div class="uploads" v-if="otherimg!=''" @click="upload">
<img :src="otherimg" alt />
</div>
<div class="upload" v-else @click="upload">
<span>+</span>
<p>添加名片或相關圖片</p>
</div>
</div>
css樣式
.input-up {
padding: 0.26rem 0.18rem;
}
.input-up .upload {
width: 2.36rem;
height: 1.4rem;
border: 1px solid #f5f5f5;
}
.input-up .upload span {
display: block;
text-align: center;
font-size: 0.6rem;
color: #d8d8d8;
}
.input-up .uploads {
width: 1.4rem;
height: 1.4rem;
border: 1px solid #f5f5f5;
}
.input-up .uploads img {
display: block;
width: 100%;
height: 1.4rem;
}
.input-up .upload p {
text-align: center;
font-size: 0.2rem;
color: #d8d8d8;
}
接口請求用的是axios
<script>
import { Toast } from 'mint-ui' // mint-ui的彈窗提示
export default {
data () {
return {
customer_id:"",
otherimg:"",
imgData: [] // 選擇圖片保存數(shù)組
}
},
methods: {
//圖片change事件
changeImg () {
// 上傳圖片事件
var files = this.$refs.input.files
var that = this
function readAndPreview (file) {
if (file !== undefined) {
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader()
reader.onload = function (e) {
// 避免重復上傳同個圖片
if (that.imgData.indexOf(e.target.result) === -1) {
that.imgData.push(e.target.result)
that.otherimg = that.imgData.pop() //每次展示最后一個上傳的圖片
} else {
Toast('已有該圖片')
}
}
reader.readAsDataURL(file)
}
}
}
readAndPreview(files[0])
if (files.length === 0) {
return false
}
console.log(that.imgData)
that.uploadFile(files[0]) // 文件上傳服務器
},
// 圖片上傳接口
uploadFile (file) {
this.formData = new FormData()
// 添加文件流
this.formData.append('files', file, file.name)
//添加接口的參數(shù) 看需求傳或不傳
this.formData.append('user_token', localStorage.getItem('user_token'))
this.formData.append('customer_id', this.customer_id)
this.axios.post('/customerinfo/uploadImg',
headers: {
'Content-Type': 'multipart/form-data'
},
this.formData
).then(res => {
if (res.code === 0) {
//返回圖片的地址res.data
this.otherimg = res.data
Toast('上傳成功')
}
})
},
upload () {
// 點擊觸發(fā)按鈕
this.$refs.input.dispatchEvent(new MouseEvent('click'))
}
}
}