簡體   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?

節點服務器如下所示:

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

我使用express進行post get等操作,並且處理傳入的文件請求和文件系統fs非常困難。 我正在使用使用aws EC2實例上托管的node.js服務器的ac#桌面應用程序,我的程序的其余部分都可以工作,但似乎無法使上傳文件正常工作。

有人可以幫助我,給我鏈接教程或向我展示如何做嗎? 我已經使用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;
}

這對我有用

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