一、实现效果
上传图片的过程:
- 1、点击页面的某个元素
- 2、弹出弹窗
- 3、选择图片
- 4、获取图片文件
- 5、文件上传
二、思路
- 1、自定义上传样式+input
- 2、隐藏input,设置input的透明度为0
- 3、点击页面上的某个dom元素的,去获取input元素,并触发input元素的click事件
- 4、通过input的onchange事件,获取到选择的文件
<script>
import { ref } from 'vue'
const handleAddImg = () => {
const input = document.querySelector('#upload') as any
input.click()
}
const handleUploadFile = async (value: any) => {
const files = value.target.files
console.log('debug===>获取上传文件',files)
const formData = new FormData()
Array.from(files).forEach((item: any) => {
formData.append('files', item)
})
//TODO调用后端接口,传入文件参数
const { data , code } = await API.fetchImageURl(formData)
if(code == 200){
//TODO
}
}
</script>
<div class="content">
<div class="main" @click="handleAddImg">
<img src="@/assets/images/demo.png" class="img" />
<text class="title">点击上传图片</text>
</div>
<input
id="upload"
ref="fileInput"
class="img-input"
type="file"
:multiple="true"
@change="handleUploadFile"
/>
</div>
</template>
<style lang="less" scoped>
.content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
.main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.img {
width: 120px;
height: 80px;
}
.title {
font-size: 14px;
}
.img-input {
opacity: 0;
}
}
</style>