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

时间:2017-11-04 10:10:53

标签: javascript c# node.js electron restsharp

我将应用程序从c#转换为电子,当我尝试在服务器(而非我的服务器)上发送图像请求时,我遇到了一些问题。

对于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,身体响应告诉我没有选择图像。因此请求正在运行,但发送图像并不是。

2 个答案:

答案 0 :(得分:0)

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

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'
  });

答案 1 :(得分:0)

我一直在尝试使用相同的技术使用Electron将文件上传到我的localhost测试服务器,但没有运气。我的代码在控制台中返回成功,但是没有上传任何文件。这是你遇到的事情,还是有什么你可以看到我做的不同?

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>