我正在尝试将任何文件从Java控制台应用程序上传到ASP.NET MVC Web应用程序。 为此,我使用的是Apache HttpClient库。
ConsoleApplication.java
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:52031/home/DataPost");
File file = new File("A.txt");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "multipart/form-data");
mpEntity.addPart("file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
httpclient.getConnectionManager().shutdown();// Get the response
BufferedReader rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
String line = "";
StringBuilder builder=new StringBuilder();
while ((line = rd.readLine()) != null)
{
builder.append(line);
}
System.out.println(builder.toString());
ASP.NET HomeController.cs
[HttpPost]
public string DataPost(HttpPostedFile file)
{
return file.FileName.ToString();
}
我仔细调试了上面的代码,发现java程序正确访问DataPost方法,但无法上传文件,因为文件参数在方法中为null。 我谷歌关于它,并在java httpclient上发现了一些stackoverflow问题,但没有一个问题是关于服务器端实现。 请告诉我,我做错了。 感谢