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

时间:2013-05-14 19:20:55

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

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

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

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

java code snippet:

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#中创建命名参数以上传文件内容

谢谢。

2 个答案:

答案 0 :(得分:1)

转到以下链接。它可能会对您有所帮助

http://www.tangiblesoftwaresolutions.com/Product_Details/Java_to_CSharp_Converter.html?gclid=CJ-vu9if46wCFUoa6wodvW-CoA

或者您可以从Java语言转换助手(JLCA)获得帮助 点击此链接http://support.microsoft.com/kb/819018

答案 1 :(得分: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