简体   繁体   English

如何使用WebRequest从ac#Windows表单将文件上传到node.js服务器(使用强大)?

[英]How to upload a file to a node.js server (using formidable) from a c# windows form using webRequest?

The node server looks like this: 节点服务器如下所示:

app.post('/api/upload', function(req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    var oldpath = files.filetoupload.path;
    var newpath = 'C:/Users/Phili/Desktop/' + files.filetoupload.name;
    fs.rename(oldpath, newpath, function (err) {
      if (err) throw err;
      res.write('File uploaded and moved!');
      res.end();
    });
  });
});

I uses express for post get etc, and formidable to handle incoming file requests and file-system fs. 我使用express进行post get等操作,并且处理传入的文件请求和文件系统fs非常困难。 I'm working on ac# desktop app that uses the node.js server that is hosted on an aws EC2 instance, the rest of my program works, but I cannot seem to get the upload file to work. 我正在使用使用aws EC2实例上托管的node.js服务器的ac#桌面应用程序,我的程序的其余部分都可以工作,但似乎无法使上传文件正常工作。

Can someone please help me, link me a tutorial or show me how to do it? 有人可以帮助我,给我链接教程或向我展示如何做吗? I've handled the rest of the program in C# with Webrequests as follows, but I cannot seem to get the correct way to upload the file 我已经使用Webrequests按照以下方法在C#中处理了程序的其余部分,但是我似乎无法获得上载文件的正确方法

public string sendToServer(string method, string urlEx, string[] headerKey, string[] headerVal)
{
    string URL = "http://34.253.45.82:8080" + urlEx;
    var request = WebRequest.Create(URL);
    request.ContentType = "application/json; charset=utf-8";
    string text;
    request.Method = method;

    for (int i = 0; i < headerKey.Length; i++)
    {
        request.Headers.Add(headerKey[i], headerVal[i]);
    }

    var response = (HttpWebResponse)request.GetResponse();

    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        text = sr.ReadToEnd();
    }

    return text;
}

This works for me 这对我有用

using (HttpClient httpClient = new HttpClient())
using (var multiPartContent = new MultipartFormDataContent())
{
     var fileContent = new ByteArrayContent(image);
     fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
     {
         FileName = attachementname
     };
     multiPartContent.Add(fileContent);
     HttpResponseMessage response = await httpClient.PostAsync(url, multiPartContent);

     Stream body = await response.Content.ReadAsStreamAsync();
     .....

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM