使用 Node js 和 electron 上传图片。 (从 C# 代码转换)

Upload image using Node js and electron. (convert from c# code)

我正在将一个应用程序从 C# 转换为 Electron,当我尝试请求在服务器(不是我的服务器)上上传图像时遇到了一些问题。

对于 c#,我使用了 RestSharp 库并且一切正常。

    private void UploadImage(string id)
    {
        RestClient client = new RestClient("https://www.website.com")
        {
            CookieContainer = new CookieContainer()
        };
        string path = @"D:\Downloads\image.jpg";

        var request = new RestRequest("/upload?id=" + id, Method.POST);
        request.AddFile("myfile", File.ReadAllBytes(path), Path.GetFileName(path), "image/jpeg");

        request.AddHeader("Content-type", "application/json");
        request.AddHeader("Accept", "application/json");
        request.RequestFormat = DataFormat.Json;

        client.Execute(request);
    }

如何在 Node js 中转换此代码?我唯一能找到的是上传到他们自己的服务器的代码,但对我不起作用。

这是我在 Node js 中尝试过的

var fs = require('fs');
    var request = require('request');
    fs.createReadStream("D:\Downloads\image.jpg").pipe(request.post("https://www.website.com/upload?id=" + productId, function (error, response, body) {
        if (error) {
            console.log(error);
        } else {
            console.log(response);
        }
    }));

使用上面的代码我得到状态代码 200,body 响应告诉我没有图像 select。所以请求有效,但发送图像无效。

这就是我为了解决问题所做的。也许它也会对其他人有所帮助。

var fs = require('fs');
var request = require('request');

var req = request.post(uploadURL, function (err, resp, body) {
    if (err) {
      console.log('Error!');
    } else {
      console.log('URL: ' + body);
    }
  });
  var form = req.form();
  form.append('myfile', fs.createReadStream("path\to\image.jpg"), {
    filename: "image.jpg",
    contentType: 'image/jpeg'
  });

我一直在尝试使用与 Electron 相同的技术将文件上传到我的本地主机测试服务器,但没有成功。我的代码 returns 在控制台中显示成功,但从未上传任何文件。这是您遇到的事情吗,或者您是否可以看到我做的不同?

const fs = require('fs');
const request = require('request');

var uploadURL = 'http://localhost:80/sandbox/img';

var req = request.post(uploadURL, function (err, resp, body) {
    if (err) {
        console.log(err);
    } else {
        console.log(body);
    }
});

var form = req.form();

form.append('upload', fs.createReadStream("C:/nodejs/dave/assets/img/brand_logos/logo.jpg"), {
    filename: "logo.jpg",
    contentType: 'image/jpeg'
});

以下是我收到的回复,我假设这是预期的...

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://localhost/sandbox/img/">here</a>.</p>
<hr>
<address>Apache/2.4.27 (Win64) PHP/7.0.23 Server at localhost Port 80</address>
</body></html>