el-upload上传图片

1:封装上传图片组件
<template>
 <el-form :model="form">
    <el-form-item label="" :label-width="formLabelWidth" style="float:left;" >
      <el-upload
        ref="upload"
        :action="uploadurl"
        accept="image/png,image/gif,image/jpg,image/jpeg"
        list-type="picture-card"
        :limit=limitNum
        :auto-upload="false"
        :on-exceed="handleExceed"
        :before-upload="handleBeforeUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="uploadSuccess"
        :file-list="fileList"
        >
           <el-icon style=""><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button size="small" type="default"  @click="uploadFile" style="margin-left:10px;margin-top:30px;color:white;">上传到服务</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name:"DS",
  data() {
    return{
      uploadurl:  process.env.VUE_APP_AXIOS_BASEURL+ process.env.VUE_APP_AXIOS_API+"/Upload/Image",
      fontsize:'0px',
      formLabelWidth: '0px',
      limitNum: 1,
      form: {},
      fileList:[]
    }
  },
  props:["logourl"],//接收父组件传过来的logo图片路径
  methods: {
    // 上传文件之前的钩子
    handleBeforeUpload(file){
      console.log('before')
      if(!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
      }
      let size = file.size / 1024 / 1024
      if(size > 5) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小不能大于5M'
        })
      }
    },
    updateUrl(val){
    this.fileList=[];//置空图片
     this.$emit('update:logourl',val)//给首页的logo复制
    if(val){
      this.fileList.push({ url: val});//只有不为空的时候才会有默认图片
      }
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
       console.log(files, fileList);
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.$emit('update:logourl','')
      console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      console.log(file)
    },
    uploadFile() {
      this.$refs.upload.submit()
    },
    uploadSuccess(obj){
       if (obj.success) {
          //图片上传成功以后改变父组件的值,这里的logourl对应父组件里面的logo
           this.$emit('update:logourl',obj.data.src )
       } else {
    // this.$message.error('操作失败')
  }
    }

  }
}
</script>
<style>
               .el-upload--picture-card{
                    width: 100px;
                    height: 100px;
                }
                 .el-upload{
                    width: 100px;
                    height: 100px;
                   
                     
                }
                .el-upload-list--picture-card .el-upload-list__item{
                    width: 100px;
                    height: 100px;
                    line-height: 100px;
                }
                .el-upload-list--picture-card .el-upload-list__item-thumbnail{
                    width: 100px;
                    height: 100px;
                    line-height: 100px;
                }
                .avatar{
                    width: 100px;
                    height: 100px;
                }
</style>
 
2:调用组件
<template>
  <!--信用等级管理-->
  <el-space wrap class="w100" id="search-info">
    <el-space class="search-input400">
      <div>银行名称:</div>
      <el-input v-model="bankName"></el-input>
    </el-space>
  </el-space>
  <div class="w100 mgt flex-row-between" id="search-button">
    <el-button type="primary" @click="loadData(1)">查询</el-button>
    <el-button type="primary" @click="addItem">添加</el-button>
  </div>
  <el-table v-loading="loading" class="mgt w100" stripe :data="tableData" style="flex: 1" border :height="contentHeight">
    <el-table-column prop="bankName" label="银行名称" width="360" align="center"></el-table-column>
    <el-table-column prop="bankCode" label="银行编码" width="320" align="center"></el-table-column>
    <el-table-column prop="isEnable" label="是否启用" width="320" align="center">
      <template #default="scope">
        {{ scope.row.isEnable=="1"?"启用":"禁用"}}
      </template>
    </el-table-column>
    <el-table-column prop="" label="操作" align="center" width="130"  fixed="right">
      <template #default="scope">
        <el-space>
          <el-button type="primary" size="small" plain @click="updItem(scope.row)">修改</el-button>
          <el-button type="danger" size="small" plain @click="delItem(scope.row)">删除</el-button>
        </el-space>
      </template>
    </el-table-column>
  </el-table>
  <!--  </div>-->
  <div class="w100 flex-row-end mgt" id="page">
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"/>
  </div>


  <el-dialog v-model="windowStatus" v-loading="windowSaving" width="600px">
    <el-space direction="vertical">
      <el-space>
        <div class="in-title">银行名称:</div>
        <el-input class="in-input" v-model="editItem.bankName"></el-input>
      </el-space>
      <el-space>
        <div class="in-title">银行编码:</div>
        <el-input class="in-input" v-model="editItem.bankCode"></el-input>
      </el-space>
      <el-space>
        <div class="in-title">是否启用:</div>
      <el-radio-group v-model="editItem.isEnable"  class="in-input">
        <el-radio label="1" >启用</el-radio>
        <el-radio label="0" >禁用</el-radio>
      </el-radio-group>
      </el-space>
        <el-space>
            <div class="in-title" style="margin-left:-60px;" >银行logo:</div>
              <upload-picture  v-model:logourl="logo" ref="child">

              </upload-picture>
        </el-space>


      <el-space>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </el-space>
    </el-space>
  </el-dialog>
</template>

<script>
import uploadFile  from "../../components/uploadPicture.vue"
  export default {
    name: "bank-manager",
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.getTableHeight();
        vm.loadData(1)
      })
    },
    data() {
      return {
      //: 'http://localhost:8003/v1/Upload/Image',
        bankName: '',
        contentHeight: '0px',
        pageIndex: 1,
        pageSize: 20,
        total: 0,
        tableData: [],
        loading: false,
        windowStatus: false,
        editItem: {isEnable:"0",logo:''},
        windowSaving: false,
        logo:'',
      }
    },
  components: {
  "upload-picture":uploadFile
  },
    methods: {
      // 上传前,限制的上传图片大小
      beforeImageUpload(rawFile){
                if(rawFile.size / 1024 / 1024 > 10){
                    this.$message.error("单张图片大小不能超过10MB!");
                    return false;
                }
                return true;
            },
            // 上传成功,获取返回的图片地址
            handleUpImage(res){
                this.editItem.logo = res.data.url;
            },
      delItem(item) {
        this.$msgbox({
          title: '提示',
          message: '确认删除' + item.levelName + '?',
          showCancelButton: true,
          beforeClose: (action,instance,done) => {
            if (action == 'confirm') {
              this.loading = true;
              this.$Http.post('AdminBank/BankDelete', {id: item.id}).then(() => {
                this.loadData();
                done();
              }).catch(res => {
                this.$message.error(res.data.message);
                this.loading = false;
              })
            } else {
              done();
            }
          }
        })

      },
      saveItem() {
        if (!this.editItem.bankName) {
          this.$message.error('请输入银行名称');
          return;
        }
        if (!this.editItem.bankCode) {
          this.$message.error('请输入编码');
          return;
        }
        if (this.$ObjectUtil.isEmpty(this.editItem.isEnable)) {
          this.$message.error('请选择是否启用');
          return;
        }
        this.windowSaving = true;
        this.editItem.logo=this.logo;//图片路径
        if (this.editItem.id) {
          this.$Http.post('AdminBank/BankUpdate', this.editItem).then(() => {
            this.windowStatus = false;
            this.loadData()
          }).catch(res => {
            this.windowSaving = false;
            this.$message.error(res.data.message)
          })
        } else {
          this.$Http.post('AdminBank/BankCreate', this.editItem).then(() => {
            this.windowStatus = false;
            this.loadData()
          }).catch(res => {
            this.windowSaving = false;
            this.$message.error(res.data.message)
          })
        }

      },
      addItem() {
        this.editItem = {};
        this.windowStatus = true;
        this.windowSaving = false;
        this.editItem.isEnable ='1';
      },
      updItem(item) {
        setTimeout(()=>{
          this.$refs.child.updateUrl(item.logo)
        },10)
     
        this.windowStatus = true;
        this.windowSaving = false;
        this.editItem = JSON.parse(JSON.stringify(item));
        this.editItem.isEnable =''+ item.isEnable+'';
       
      },
      getTime(time) {
        return this.$DateUtil.formatUnix(time / 1000);
      },
      getTableHeight() {
        this.$nextTick(() => {
          let searchInfo = document.getElementById('search-info');
          let searchButton = document.getElementById('search-button');
          let page = document.getElementById('page');

          let height = searchInfo.offsetHeight + searchButton.offsetHeight + page.offsetHeight + 24 + 'px';

          this.contentHeight = 'calc(100% - ' + height + ')'
        })
      },

      loadData(page) {
        let param = {};
        if (this.bankName) {
          param.bankName = this.bankName;
        }
        if (page) {
          this.pageIndex = page;
        }
        param.pageIndex = this.pageIndex;
        param.pageSize = this.pageSize;
        this.loading = true;
        this.$Http.get('AdminBank/GetBankPagedList', {params: param}).then(res => {
          this.tableData = res.data.data.items;
          this.total = parseInt(res.data.data.totalCount);
          this.loading = false;
        }).catch((res) => {
          this.$message.error(res.data.data.message);
          this.loading = false;
        })
      }
    }
  }
</script>

<style scoped>
  @import "/src/commcss/flex.css";
  @import "/src/commcss/background.css";

</style>
3:后端上传图片

/// <summary>
/// 图片上传
/// </summary>
/// <param name="file"></param>[FromBody]
/// <returns></returns>
[HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue)]
public async Task<object> Image(IFormFile file)
{

try
{
if (file != null)
{
var isSaveLocal = false; // 本地是否保存
var savePath = string.Empty;
var rootDir = "uploads";
var saveDate = DateTime.UtcNow.ToString("yyyyMMdd");
// var saveUser = $"{type}_{CurrentUser.Id}";
var txt = Path.GetExtension(file.FileName).ToLower();
var saveFilePath = string.Empty;
var saveFilename = Guid.NewGuid().ToString("N") + txt;
var src = string.Empty;
var img = new string[] {".jpg", ".png", ".jpeg", ".mp4"};
if (!!!img.Contains(txt))
throw new MyException("仅支持JPG、JEPG、PNG、MP4的格式");
if (file.Length > 50 * 1204 * 1000)
throw new MyException("请上传50M以下的文件");

// savePath = Path.Combine(_hostingEnvironment.WebRootPath, rootDir, Tid, saveUser, saveDate);
src = $"/{rootDir}/{saveDate}/{saveFilename}";

var alibabaSetting = await _settingService.GetSetting<AlibabaCloudSetting>();

var bucketName = alibabaSetting.BucketName;
var endpoint = alibabaSetting.Endpoint; 
var accessKeyId = alibabaSetting.AccessKeyId; 
var accessKeySecret = alibabaSetting.AccessKeySecret;
var staticUrl = alibabaSetting.StaticUrl;

// saveFilePath, 文件保存在服务器的位置
var ossClient = new OssClient(endpoint, accessKeyId, accessKeySecret);
if (isSaveLocal)
{
var ossResult = ossClient.PutObject(bucketName, src.TrimStart('/'), saveFilePath);
}
else
{
var ossResult = ossClient.PutObject(bucketName, src.TrimStart('/'), file.OpenReadStream());
}

return new {src = staticUrl.UriCombine(src)};
}
else
{
throw new MyException("上传文件为空");
}
}
catch (Exception e)
{
throw new MyException(e.Message);
}
}

posted @   yingxianqi  阅读(193)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示