首页 > 解决方案 > 如何在电子应用程序中本地保存图像

问题描述

我正在使用vue-cli-electron-builder 构建一个电子应用程序。

用户提交包含姓名、电子邮件和图像(照片)的表单,这些表单存储在本地 mysql 数据库中,稍后将同步到云端。只有图像名称将存储在数据库中,问题是

在开发模式下,它存储在项目中,但生产捆绑的应用程序不能那样工作。

我尝试 multer.diskStorage 将图像保存到“./server/uploads”。它在开发模式下工作,但在生产中它不起作用。

标签: javascriptmysqlexpressvue.jselectron

解决方案


您可以将上传的内容存储在userAppData文件夹中。你应该尝试如下

function uploadFile() {
    dialog.showOpenDialog({
          properties: ['openFile','multiSelections'],
          filters: [{
             name: 'Images',
             extensions: ['jpg', 'png', 'gif']
          }]
       },
       uploadF, //define callback 
    )
}
function uploadF(filePaths) {
    if (filePaths!=undefined) {
        //multiple image upload
        for (let i = 0; i < filePaths.length; i++) {
            let fileName = path.basename(filePaths[i])
            fileName = moment().unix()+'-'+fileName //rename file
            let fileUploadPath = app.getPath('userData')+ '' + fileName;
            move(filePaths[i],fileUploadPath,cb)
        }
    }
}
function cb(e) {
    console.log("error in upload file",e);
}
function move(oldPath, newPath, callback) {
    fs.rename(oldPath, newPath, function (err) {
        if (err) {
        if (err.code === 'EXDEV') {
            copy();
        } else {
            console.log("err",err);

            callback(err);
        }
        return;
        }
        callback();
    });
    function copy() {
        var readStream = fs.createReadStream(oldPath);
        var writeStream = fs.createWriteStream(newPath);
        readStream.on('error', callback);
        writeStream.on('error', callback);

        readStream.on('close', function () {
            let fileName=path.basename(newPath)
            console.log(fileName,"  file uploaded")
            //remove path from destination
            //fs.unlink(oldPath, callback);
            // do your stuff
        });
        readStream.pipe(writeStream);
    }
}

推荐阅读