vant中自定义文件上传+js自定义上传(点击区域上传并预览)

mac2026-01-16  8

首先是普通的vant文件上传

<van-uploader multiple v-model="fileList" accept=image/jpeg :max-count="1" :after-read="afterRead" ref="selectfile" /> data(){ return{ filelist:[], } } methods: { // 用表单提交 afterRead(file) { //文件读取完成后的回调函数 let content = file.file; //创建一个新的FormData let formData = new FormData(); // upload这个名字是后台给的 formData.append("upload", content); //获取formdata表单所有的数据 console.log(formData.getAll("")); // axios // .post( //服务器上传地址 // `http://xxxxxxxxxxxx`, //服务器需要的数据,此处是formdata表单 // formData,(名字是后台参数确定的) //如果默认请求头是json,需要改一下请求头数据格式 // { // "Content-Type": "multipart/form-data" // } // ) // .then(res => { // console.log(res); // console.log(res.config.headers); // }); axios({ method: "post", //服务器上传地址 url: `http://xxxxxxxxxxxxxxxxxxxxxxxxxxx`, data: formData,//(名字是后台接口参数确定的) headers: { // 修改请求头 "Content-Type": "multipart/form-data" } }).then(res => { console.log(res); console.log(res.config.headers); }); } }

划重点(⊙_⊙)—耗费了我几个小时才搞出来的点击整个区域就可以上传的代码, (*๓´╰╯`๓)

自定义文件上传

点击整个红色区域触发启动本地文件夹 选中图片之后,依然在对应区域预览

HTML代码 使用vant , (`・ω・´)

<li @change="changeImage($event)"> <van-uploader multiple :accept="'image/*'" :preview-size="30" :deletable="false" :after-read="afterRead" > <span>修改头像</span> <img :src="avatar" class="img-avatar" /> <van-icon name="arrow" /> </van-uploader> </li> **js代码** data() { return {avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',} } methods: { changeImage(e) { const file = e.target.files[0]; const reader = new FileReader(); const that = this; reader.readAsDataURL(file); reader.onload = function () { that.avatar = this.result; }; }, }

**不使用vant , (~ ̄▽ ̄)~ ** 1.html代码 っ゚Д゚)っ

<div class="rz-picter"> <img :src="avatar" class="img-avatar"> <input type="file" name="avatar" id="uppic" accept="image/gif,image/jpeg,image/jpg,image/png" @change="changeImage($event)" ref="avatarInput" class="uppic"> </div>

2.js代码 (ㅍ_ㅍ)

data() { return { avatar: require('../assets/jia.jpg'), } },

3.实现函数 O(∩_∩)O

changeImage(e) { var file = e.target.files[0] var reader = new FileReader() var that = this reader.readAsDataURL(file) reader.onload = function(e) { that.avatar = this.result } },

(ง •_•)ง

最新回复(0)