【问题标题】:Electron, copy a file to the websrver folderElectron,将文件复制到 websrver 文件夹
【发布时间】:2019-03-21 13:58:54
【问题描述】:

我正在使用电子的对话框来访问用户的文件,现在我想将选定的文件上传到网络服务器。在我的代码中,我使用了fs.copyFile,但它向我显示了一个错误,因为它将项目路径添加到http://localhost/upload

我会很高兴得到任何帮助。谢谢

dialog.showOpenDialog(dialogOptions,function(fileNames) {
        // fileNames is an array that contains all the selected 
        if (fileNames === undefined) {
            console.log("No file selected");

        } else {
            readFile(fileNames[0]);
        }
    });

    function readFile(filepath) {
        fs.readFile(filepath, 'utf-8', (err, data) => {
            if (err) {
                alert("An error ocurred reading the file :" + err.message)
                return
            }

            fileName = pathf.basename(filepath);
            // Copy the chosen file to the application's data path
            fs.copyFile(filepath, 'http://localhost/upload/' + fileName, (err) => {
               if (err) throw err;
           });

            // handle the file content 
            event.sender.send('fileData', data)
            event.sender.send('fileDataPath', filepath)

        })
    }

【问题讨论】:

  • 您是否有一个 Web 服务器在本地侦听某个特定端口,并且有一个 API 端点等待您的上传请求?
  • 是的。像这样 require('http').createServer(function (request, res) { request.addListener('end', function () { file.serve(request, res) res.writeHead(200, { 'Content-Type' : 'text/html' }); res.write('
    '); res.write('
    ') ; return res.end(); }).resume() }).listen(9990)

标签: javascript node.js localhost electron


【解决方案1】:

这可以通过从 Electron 应用以multipart/form-data 的形式发送数据到网络服务器来实现。

您可以使用Express 这是一个最小的Web 框架与multer express 中间件一起通过multipart/form-data 接受文件上传,因为您不能只是将文件复制到Web 服务器。在客户端(Electron)上,您必须使用一些 http 客户端库(例如 Axios)通过网络将文件数据发送到 Web 服务器。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2014-12-03
    • 2012-01-14
    • 2010-10-28
    相关资源
    最近更新 更多