问题:我有一个 Java spring rest 服务来上传文件(大尺寸)。我想使用 .NET httpClient(或其他 .net 客户端)来调用上传服务。
问题:
- 似乎发送大文件的最佳选择是多部分文件,互操作性是什么?
- 如果不可能,最好的选择是什么?
谢谢!
问题:我有一个 Java spring rest 服务来上传文件(大尺寸)。我想使用 .NET httpClient(或其他 .net 客户端)来调用上传服务。
问题:
谢谢!
这就是答案:我可以将带有多部分附件的文件从 c# 客户端发送到 Java JAX Rest Webservice。
try
{
using (
var client = new HttpClient())
using (var form = new MultipartFormDataContent())
{
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using (var fileContent = new StreamContent(stream)) {
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {FileName = fileName, DispositionType = DispositionTypeNames.Attachment, Name = "fileData"};
form.Add(fileContent);
// only for test purposes, for stable environment, use ApiRequest class.
response = client.PostAsync(url, form).Result;
}
}
}
return response.RequestMessage != null ? response.ReasonPhrase : null;
}
catch (Exception ex)
{
TraceManager.TraceError("Post Asyn Request to " + url + " \n" + ex.Message, ex);
throw;
}
HTTP 是一个独立于操作系统平台和编程语言的标准,因此如果您的 .net 客户端符合标准,则互操作性应该不会有任何问题。
java 弹簧启动
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String upload(@RequestParam("FileParam") MultipartFile file){
InputStream fromClient=file.getInputStream();
...do stuff with the database/ process the input file...
C#
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
FileInfo file = new FileInfo(@"<file path>");
form.Add(new StreamContent(file.OpenRead()),"FileParam",file.Name);
HttpResponseMessage response = await client.PostAsync("http://<host>:<port>/upload", form);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.ToString());
Console.WriteLine(Encoding.ASCII.GetString(await response.Content.ReadAsByteArrayAsync()));