在Electron中上传和检索图像文件

时间:2018-12-30 17:04:44

标签: javascript html electron

我正在尝试在Electron中构建一个具有html表单并带有图像上传按钮的应用程序。所以我的目的是要求用户上传图像,我想将图像文件保存在应用程序的本地文件夹中的某个位置,并在需要时检索图像。我将如何实现?

2 个答案:

答案 0 :(得分:2)

更新的答案:

dialog.showOpenDialog()返回承诺

const electron = require('electron');
const { dialog } = electron;    // electron.remote; (if in renderer process)
const fs = require('fs');       // module that interacts with the file system
const path = require("path");   // utilities for working with directory paths

function uploadImageFile() {

    // opens a window to choose file
    dialog.showOpenDialog({properties: ['openFile']}).then(result => {

        // checks if window was closed
        if (result.canceled) {
            console.log("No file selected!")
        } else {

            // get first element in array which is path to file selected
            const filePath = result.filePaths[0];

            // get file name
            const fileName = path.basename(filePath);

            // path to app data + fileName = "C:\Users\John\AppData\Roaming\app_name\picture.png"
            imgFolderPath = path.join(app.getPath('userData'), fileName);

            // copy file from original location to app data folder
            fs.copyFile(filePath, imgFolderPath, (err) => {
                if (err) throw err;
                console.log(fileName + ' uploaded.');
            });
        }
    });
}

// click event to trigger upload function
// In html:  <input type="button" class="upload-image" value="Upload Image">

$(".upload-image").on("click", () => {
    uploadImageFile()
});

答案 1 :(得分:0)

如果我对您的理解正确,则打算将图像存储在用户的计算机上,因此无需进行远程上传。您只需要将文件从其原始位置复制到应用程序本地数据路径。

要实现此目的,您可以在表单中添加一个按钮,该按钮将首先触发dialog,以使用户浏览该文件。 然后,您将copy所选文件local data path到应用程序。 之后,该想法将是存储有关图像文件的一些信息,以便您可以检索它以供以后使用。

const { app, dialog } = require('electron');
const fs = require('fs');
const path = require("path");

// The function triggered by your button
function storeImageFile() {

  // Open a dialog to ask for the file path
  const filePath = dialog.showOpenDialog({ properties: ['openFile'] })[0];
  const fileName = path.basename(filePath);

  // Copy the chosen file to the application's data path
  fs.copyFile(filePath, (app.getPath('userData') + fileName), (err) => {
    if (err) throw err;
    console.log('Image ' + fileName + ' stored.');

    // At that point, store some information like the file name for later use
  });
}