【问题标题】:Upload document to Server using HttpPost使用 HttpPost 将文档上传到服务器
【发布时间】:2013-05-14 19:20:54
【问题描述】:

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

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

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

java代码sn-p:

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# 中使用命名参数来上传文件内容

谢谢。

【问题讨论】:

    标签: c# .net c#-4.0 http-post


    【解决方案1】:

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

    注意:

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

    代码:

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

    IMO 这是在 .net 上做的最干净的方式,忘掉肮脏的HttpRequests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2016-09-07
      • 2023-03-06
      • 2014-11-16
      相关资源
      最近更新 更多