Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用HttpPost将文档上载到服务器_C#_.net_C# 4.0_Http Post - Fatal编程技术网

C# 使用HttpPost将文档上载到服务器

C# 使用HttpPost将文档上载到服务器,c#,.net,c#-4.0,http-post,C#,.net,C# 4.0,Http Post,应用程序“A”需要使用POST将word文件[作为字节数组]上载到外部应用程序 filecontent应作为命名参数添加到请求正文中,并且必须发出POST请求才能上载文件 我有一个示例代码,但使用java。我想写一个等价的C代码。但在C#中,找不到类似于MultiPartEntity的对象 java代码片段: String restURL = HOSTURL + "/rest/upload/0b002f4780293c18"; String fileName = "testRes

应用程序“A”需要使用POST将word文件[作为字节数组]上载到外部应用程序

filecontent应作为命名参数添加到请求正文中,并且必须发出POST请求才能上载文件

我有一个示例代码,但使用java。我想写一个等价的C代码。但在C#中,找不到类似于MultiPartEntity的对象

java代码片段:

String restURL = HOSTURL + "/rest/upload/0b002f4780293c18";        
String fileName = "testRestUploadByFolderID" + Calendar.getInstance().getTimeInMillis() + ".txt";        
File testFile = createNewFile("C:/Temp/rest/" + fileName);        
FileBody content = new FileBody(testFile, "application/octet-stream");        
System.out.println(" File Name : " + content.getFilename() + " ... "                +     content.getTransferEncoding());        
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);        
reqEntity.addPart("filename", new StringBody(fileName));        
reqEntity.addPart("uploadfile", content);        
HttpPost httpPost = new HttpPost(restURL);        
httpPost.addHeader("Accept", "application/json");        
httpPost.setEntity(reqEntity);                 

// Post the request        
String response = httpclient.execute(httpPost, new DefaultResponseHandler());
你可以发布一些链接来解释如何在C#中创建命名参数来上传文件内容吗


谢谢。

如果您正在寻找一篇多部分内容的帖子,也许这会有帮助:

注意:

这是.net 4.5异步方式,但您也可以在.net 4中使用此解决方案安装一些Nuget软件包:

代码:

在我看来,这是在.net上做这件事的最干净的方式,忘掉肮脏吧

using (HttpClient httpClient = new HttpClient())
using (var multiPartContent = new MultipartFormDataContent())
{

     httpClient.BaseAddress = new Uri(BaseAddress);

     var fileContent = new ByteArrayContent(*filebytes*);

     //Create content header
     fileContent.Headers.ContentDisposition = new ontentDispositionHeaderValue("attachment")
                {
                    FileName = *fileName*
                };

       //Add file to the multipart request
       multiPartContent.Add(fileContent);

       //Add any other file?
       ...


      //Post it
      HttpResponseMessage response = await httpClient.PostAsync("hostURL", multiPartContent);

 }