【问题标题】:Load images from local disk从本地磁盘加载图像
【发布时间】:2018-10-23 12:26:36
【问题描述】:

我目前正在使用 electron-vue 样板来接触电子。

我的目标是显示应用程序中给定文件夹中的所有图像(渲染器进程)。

<template>
  <div>
    <button @click="selectSourceDir()">Quellverzeichnis</button>
    Aktuell: {{sourcePath}}
    <button @click="scan()">Aktualisieren</button>
    <ul>
      <li v-for="image in images">
        <!--<img v-bind:src="'data:image/jpg;base64,' + image.base64">-->
        <img v-bind:src="'file://' + image.path">
      </li>
    </ul>
    
  </div>
</template>

<script>
  import ImageFile from './ImageDispatchPage/ImageFile';
  import fs from 'fs';
  import { ipcRenderer as ipc } from 'electron';
  import path from 'path';

  export default {
    name: 'image-dispatch-page',
    components: { ImageFile },
    data () {
      return{
        images: [],
        sourcePath: null,
      }  
    },
    methods: {     
      scan(){        
        // If path is not set do nothing
        if(!this.sourcePath){
          return;
        }
        // Iterate over all files in directory
        let files = fs.readdirSync(this.sourcePath);
        const regex = /.jpe?g$/gmi;        
        for (let file of files){          
          // Ignore non jpg files                    
          if(!file.match(regex)){
            continue;                                    
          }          
          let image = {};
          image.name = file;
          image.path = path.join(this.sourcePath, file);
          image.base64 = new Buffer(fs.readFileSync(image.path)).toString('base64');       
          this.images.push(image);
        }        
      },
      selectSourceDir(){
        ipc.send('open-directory-dialog');        
        ipc.on('selected-directory', (event, directory) => {
          this.sourcePath = directory;         
        });        
      }
    },
    created(){
      this.scan();
    } 
  }
</script>

<style scoped>
  
</style>

运行此代码会导致以下错误消息: 如果我将注释掉的行与非常慢的 base64 编码图像一起使用(第 8 行),则一切正常。

简单地显示这些图像的正确解决方案是什么?

【问题讨论】:

  • 使用图片的相对文件路径,而不是 URL(我没有投反对票)
  • 我尝试使用 app.getAppPath() 和节点 path.relative 确定图像的相对路径(不确定这是否是您的意思)-这给了我相对路径但错误消息在控制台中显示保持不变:“不允许加载本地资源”
  • 关闭网络安全:"web-preferences": { "web-security": false }
  • 谢谢兰迪!快速浏览一下文档会发现与当前版本不同的符号。此设置是否存在任何安全问题?
  • 安全性取决于您使用应用程序执行的操作。如果您只是加载您作为应用程序的一部分控制的资源,那么不,没有真正的安全问题。否则可能会有。

标签: javascript electron electron-vue


【解决方案1】:

在我的主进程中关闭网络安全起到了作用。

mainWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    webPreferences: {
        webSecurity: false
    }
});

【讨论】:

  • 在此处添加注释,您应该仔细考虑是否真的要禁用此选项:electronjs.org/docs/tutorial/… "禁用 webSecurity 将禁用同源策略并将 allowRunningInsecureContent 属性设置为 true。换句话说,它允许执行来自不同域的不安全代码。”
猜你喜欢
  • 2022-06-27
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多