我一直在寻找这个答案,但却找不到任何有效的解决方案。
我尝试从安卓应用程序上传图片到Java Servlet并将其保存在服务器上。但是我发现所有的解决方案都对我无效。
目前我的代码实现方式是:安卓应用程序将图片发送到Servlet,当我尝试将其保存时,文件被创建了,但是它是空的:(
谢谢你的帮助!
以下是我的Android客户端代码(i_file是设备上文件的位置):
我尝试从安卓应用程序上传图片到Java Servlet并将其保存在服务器上。但是我发现所有的解决方案都对我无效。
目前我的代码实现方式是:安卓应用程序将图片发送到Servlet,当我尝试将其保存时,文件被创建了,但是它是空的:(
谢谢你的帮助!
以下是我的Android客户端代码(i_file是设备上文件的位置):
public static void uploadPictureToServer(String i_file) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://192.168.1.106:8084/Android_Server/GetPictureFromClient");
File file = new File(i_file);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
我的服务器端代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
InputStream in = request.getInputStream();
OutputStream out = new FileOutputStream("C:\\myfile.jpg");
IOUtils.copy(in, out); //The function is below
out.flush();
out.close();
}
IOUtils.copy代码:
public static long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
processRequest
是做什么的? - homeprocessRequest
方法中会发生什么? - home