当前位置:首页 » 《关注互联网》 » 正文

vue前端图片上传、回显图片

25 人参与  2024年04月15日 16:20  分类 : 《关注互联网》  评论

点击全文阅读


方法一(基于vue+html):

<label>文件:</label><input type="file" @change="selectFile($event)"/><button type="button" @click="upfile($event)">上传</button><div>    <img :src="'upfiles/'+filename" /></div>
<script src="js/axios.min.js"></script>    <script src="js/vue.js"></script>    <script>        const vm = new Vue({            el:"#app",            data:{                file:null,                filename:"shangchuang.png"            },            methods: {                selectFile(event){                    console.log(event);                    this.file = event.target.files[0];                },                upfile(event){                    let formdata = new FormData();                    formdata.append("file",this.file);                    axios.post("http://localhost:8080/upfile/photo",formdata,{                        "Content-type":"multipart/form-data"                    }).then((res)=>{                        console.log(res.data);                        this.filename = res.data;                    });                }            },        })    </script>

方法二(基于vue+element):

<template v-slot="scope">    <el-image :src="getAssetsFile(scope.row.reason)"></el-image></template><el-form-item label="图片" prop="reason">    <el-upload       :action="imgUrl"       :class="{ disabled: uploadDisabled }"       list-type="picture-card"       :limit="limitcount"       :on-change="handleChange"       :on-remove="handleRemove"       :show-file-list="true"       :on-success="onSuccess"       style="width: 200px;margin-left: 54px">    </el-upload>    <el-dialog :visible.sync="dialogVisible">       <img v-if="dialogImageUrl" width="100%" :src="dialogImageUrl" alt="">       <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>    </el-dialog></el-form-item>
return{    imgUrl:'http://localhost:8080/mainupfile/photo',//文件上传访问后端的路径    dialogImageUrl: null,    dialogVisible: false,    uploadDisabled: false,    limitcount: 1,}methods:{    /** 回显图片 */    getAssetsFile(url){      return new URL(`../../assets/upload/${url}`, import.meta.url).href    },    /**选择图片*/    handleChange(file, fileList) {      this.uploadDisabled = fileList.length >= this.limitcount;      console.log("this.uploadDisabled", this.uploadDisabled);      return false;    },    /**删除图片*/    handleRemove(file, fileList) {      this.uploadDisabled = fileList.length >= this.limitcount;      console.log("this.uploadDisabled", this.uploadDisabled);    },    /**成功获取图片*/    onSuccess: function (response) {      // this.imgUrl= this.FormList;      this.dialogImageUrl = response;      //      this.FormList.reason = response    },}

方法三(基于vue+vant):

<img :src="'src/assets/upload/'+photo"><van-uploader name="file" :after-read="afterRead">    <p>从相册中选择</p></van-uploader>
const afterRead = async (file) => {    const modifiedFile = new File([file.file], '.png'); // 修改文件名为 new_filename.jpg  try {    const formData = new FormData();    formData.append('file', modifiedFile);    const response = await axios.post('http://localhost:8080/upphoto/fileUpload', formData, {      headers: {        'Content-Type': 'multipart/form-data',      },    });    console.log("图片为:"+response.data);    showToast({      type: 'success',      message: '头像上传成功',    });    photo.value = response.data;    console.log("photo:"+photo.value);    console.log("response.data:"+response.data);  } catch (error) {    console.error('头像上传失败:', error);    showToast({      type: 'fail',      message: '头像上传失败',    });  }};

图片预览效果的实现:

Element Plus官网实现:

<el-image      style="width: 100px; height: 100px"      :src="url"      :zoom-rate="1.2"      :max-scale="7"      :min-scale="0.2"      :preview-src-list="srcList"      :initial-index="4"      fit="cover"    /></div><script lang="ts" setup>const url =  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'const srcList = [  'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',  'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',  'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',  'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',  'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',  'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',  'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg',]</script><style scoped>.demo-image__error .image-slot {  font-size: 30px;}.demo-image__error .image-slot .el-icon {  font-size: 30px;}.demo-image__error .el-image {  width: 100%;  height: 200px;}</style>

如果不想用官网的方法,就自己定义事件:

<template v-slot="scope">    <el-image :src="getAssetsFile(scope.row.cardphoto)" fit="cover" style="width: 50px; height: 50px"  class="building-image" @click="openPreview(scope.row.cardphoto)"></el-image></template>//弹出图片层<el-dialog v-model="previewDialogVisible" width="30%">     <div style="display: flex;justify-content: center;align-items: center;width: 100%;height: 100%;">             <el-image :src="previewImageUrl" fit="contain" style="width: 100%; height: 100%"></el-image>     </div></el-dialog>//逻辑,我这里是使用了ts语法setupconst previewDialogVisible = ref(false);const previewImageUrl = ref('');const getAssetsFile=(url: string)=>{    return new URL(`../assets/upload/${url}`, import.meta.url).href;    // return "../assets/upload/"+ url}const openPreview = (url: string) => {  previewImageUrl.value = getAssetsFile(url);  previewDialogVisible.value = true;};


点击全文阅读


本文链接:http://zhangshiyu.com/post/95733.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1