vue自定义上传图片
1.用elementUI 里的el-upload上传
<div class="businesster">
<el-form-item label="封面图片" prop="headImg">
<div class="businesster_ying">
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:on-preview="handlePreview"
:before-upload="beforeAvatarUpload"
:http-request="uploadFile"
>
<el-button class="f_picture">点击上传</el-button>
<img
v-if="imageUrl"
:src="imageUrl"
class="avatar"
style="width: 200px"
/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</el-form-item>
<div slot="tip" class="el-upload__tip">
<p>
推荐尺寸750*272;支持.jpg, .jpeg, .bmp, .gif,
.png类型文件,5M以内
</p>
</div>
</div>
2.:http-request="uploadFile"用自定义上传
js
data() {
return {
base64img:"",
imageUrl: require("../../assets/images/andy.png"),
//默认给一张图片
}
}
methods: {
uploadFile(params){
var _this = this
console.log("uploadFile",params)
if (params.file.name) {
var reader = new FileReader();
//通过文件流将文件转换成Base64字符串
reader.readAsDataURL(params.file);
reader.onloadend = function () {
// 把转换过得base赋值给全局变量
// 这里reader.result就是转换好的bsae64格式图片
_this.base64img = reader.result;
// console.log(this.base64img);
// this.imageUrl = URL.createObjectURL(params.file)
_this.imageUrl = _this.base64img,
console.log(_this.imageUrl)
};
}
},
beforeAvatarUpload(file) {
const isJPG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
const isWebp = file.type === "image/webp";
const isGif = file.type === "image/gif";
const isBmp = file.type === "image/bmp";
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isJPG && !isPNG && !isWebp && !isGif && !isBmp) {
this.$message.error(
"上传封面图片只能是 JPG、png、GIF、JPEG、BMP、webp 格式!"
);
}
if (!isLt5M) {
this.$message.error("上封面图片大小不能超过 5MB!");
}
return (isJPG || isPNG || isWebp || isGif || isBmp) && isLt5M;
},
}
3.要注意的是uploadFile 方法没起到作用 是this指向的问题
补充一下:elementUI里的上传图片显示问题
//自定义上传方法
http_request_two(params,fileList){
console.log(params,"修改营业执照");
// 需要用URL.createObjectURL()方法转一下file,页面上图片才能加载出来
this.imageUrl = URL.createObjectURL(params.file)
},