【发布时间】:2012-05-20 01:18:26
【问题描述】:
我一直在寻找这个,但没有任何对我有用。
我正在尝试将图像从 android 应用程序上传到 java servlet 并将其保存在服务器中。 我发现的每个解决方案都对我不起作用。
我的代码目前在做什么:android 应用正在将图像发送到 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;
}
【问题讨论】:
-
这不仅与客户端有关,您还必须在服务器(servlet)上实现它。顺便说一句:
processRequest是做什么的? -
感谢您的回复。我阅读了链接中的信息,但似乎无法找到解决问题的方法。
-
您的 servlet 代码是什么样的?
processRequest会发生什么? -
processRequest() 什么也没做,所以我删除了它。在这里得到了答案。感谢您的帮助@home。
标签: java android image servlets