electron上傳圖片

渣渣前端發表於2020-10-19

使用elementui元件上傳圖片

渲染程式

<template>
  <div class="hello">
   <el-upload
  class="avatar-uploader upload"
  action=""
  :show-file-list="false"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
 
  </div>
</template>

<script>
const {ipcRenderer}=window.require('electron')


import {Upload}from 'element-ui'
export default {
  name: 'HelloWorld',
  components:{elUpload:Upload,},
   data() {
      return {
        imageUrl: '',
        image:''
      };
    },
    methods: {
      async beforeAvatarUpload(file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        
    
        if (!isJPG) {
          this.$message.error('上傳頭像圖片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上傳頭像圖片大小不能超過 2MB!');
        }
       
        ipcRenderer.send('pic',file.name,file.path)
       
        return true;
      }
    }
}
</script>
<style scoped lang="scss">
.hello{width:500px;
      height:400px;
      margin:20px auto;
       border: 1px solid deeppink;
     .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    width: 100%;
    height: 100%;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>

主程式

ipcMain.on('pic',async(e,name,paths)=>{
  console.log(path.join(__static,name))
  var read=fs.createReadStream(paths);
  var write=fs.createWriteStream(path.join(__static,name));
  await read.pipe(write);

// win.webContents.send('url','http://localhost:8081/public/'+name)
})

本來想返回上傳地址給渲染程式,但是頁面會重新整理,所以上傳完不能顯示圖片

相關文章