应用程序“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/