c# - 使用 HttpPost 将文档上传到服务器

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

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

文件内容应作为命名参数添加到请求正文中,并且必须发出 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 包:

代码:

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

关于c# - 使用 HttpPost 将文档上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16551155/

相关文章:

c# - 用作控制流机制的异常在某些特定场景下是否有效?

asp.net - 连接字符串-不支持关键字:“初始目录”

c# - 有没有办法使用 LINQ 从 List<T> 中删除某些元素?

javascript - 如何从 Jquery ajax 调用中调用 HttpPost 类型的 Controller 方法

c# - Linux 上 .NET Core 的字符编码错误

c# - 在文本文件中加载和访问模板变量

c# - ServiceStack.Redis 搜索缓存

c#-4.0 - C++/CLI 接口(interface)在我的 C# 类中不可见

c# - 有没有办法在 OData 中说 "Expand Everything"?

c# - 在 ASP.Net MVC Core 2.0 中设置登录 url