| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- <template>
- <div>
- <van-uploader
- ref="uploader"
- v-bind="$attrs"
- v-model="fileList"
- :before-read="beforeRead"
- :after-read="afterRead"
- multiple
- :max-count="maxCount"
- :max-size="maxSize * 1024*1024"/>
- </div>
- </template>
- <script>
- import {upload} from "@/api/public";
- import ImageCompressor from "js-image-compressor";
- import config from '@/config/index';
- export default {
- props:{
- value:{
- type: Array,
- },
- //最大上传数量
- maxCount:{
- type: Number,
- default: 6,
- },
- //文件大小,单位MB
- maxSize:{
- type: Number,
- default: 5,
- },
- },
- data() {
- return {
- fileList:[]
- };
- },
- mounted() {
- },
- watch:{
- value:{
- handler(val){
- this.fileList = val.map(v=>{
- console.log( window.origin ,' window.origin ')
- let imgUrl =
- process.env.NODE_ENV === "development"
- ? config.baseUrl + v.imgPath
- : window.origin + v.imgPath;
- return {
- name: v.name,
- url: imgUrl,
- path:v.imgPath,
- }
- })
- },
- deep:true,
- immediate:true
- }
- },
- methods: {
- //上传前压缩
- beforeRead(file){
- console.log(file,'图片压缩前')
- return new Promise((resolve, reject) => {
- new ImageCompressor({
- file,
- quality: 0.6,
- success: (result) => {
- //this.$toast('图片压缩成功')
- console.log(result,'图片压缩后')
- let img = new File([result], result.name, {
- width: result.width,
- height: result.height,
- type: result.type,
- });
- console.log(img,'后')
- resolve(img);
- },
- error: (e) => {
- console.log('imageError:'+e);
- this.$toast('图片压缩失败')
- reject(e);
- },
- });
- });
- },
- chooseFiles(){
- console.log( this.$refs.uploader,'子组件1111')
- this.$refs.uploader.chooseFile({sourceType: ['album']})
- },
- //上传到服务器
- afterRead(fileObj){
- console.log(fileObj,'flie');
- let formData = new FormData();
- formData.append("file", fileObj.file);
- upload(formData, "image").then((res) => {
- console.log( config,'222')
- /*上传成功*/
- let imgUrl =
- process.env.NODE_ENV === "development"
- ? config.baseUrl + res.data.url
- : window.origin + res.data.url;
- let arr = [];
- let emitList=[]
- console.log(imgUrl,'imgUrl');
- arr.push({ name: res.data.name, url: imgUrl,imgPath:res.data.url});
- //emitList.push(res.data.url)
- this.fileList = arr;
- console.log(this.fileList,arr,'tttttttt')
- //emit完整图片URL路径
- this.$emit("input",arr);
- // //非完整图片URL路径
- // this.$emit("imgUrl", res.data.url);
- }).catch((err) => {
- /*上传失败*/
- console.log(this.fileList,'this.fileList')
- //this.$refs.imageUpload.handleRemove(fileObj.file);
- });
- },
- },
- model:{
- prop:'value',
- event:'input'
- }
- };
- </script>
- <style lang="scss" scoped>
- .upload-text{
- font-size: 18px;
- color: #999;
- margin-top: 5px;
- }
- </style>
|