从Android上传图像到Java Servlet并保存

6
我一直在寻找这个答案,但却找不到任何有效的解决方案。
我尝试从安卓应用程序上传图片到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;
}

这不仅涉及客户端,您还必须在服务器(servlet)上实现它。顺便问一下:processRequest是做什么的? - home
谢谢您的回复。我阅读了链接中的信息,但似乎无法找到解决我的问题的方法。 - Ohadza
你的servlet代码是什么样子的?processRequest方法中会发生什么? - home
processRequest() 没有做任何事情,所以我把它删除了。在这里找到了答案。感谢 @home 的帮助。 - Ohadza
1个回答

9
你误解了问题。图像文件不是空的,而是因为你将整个HTTP多部分请求体存储为图像文件而不是从HTTP多部分请求体中提取包含图像的部分而导致的损坏
你需要使用HttpServletRequest#getPart()来获取多部分请求体的部分。如果你已经在Servlet 3.0上(Tomcat 7,Glassfish 3等),请先使用@MultipartConfig注释你的servlet。
@WebServlet("/GetPictureFromClient")
@MultipartConfig
public class GetPictureFromClient extends HttpServlet {
    // ...
}

然后将您的doPost()修复为按名称抓取该部分,然后将其正文作为输入流:

InputStream in = request.getPart("userfile").getInputStream();
// ...

如果你还没有升级到Servlet 3.0,那么请获取Apache Commons FileUpload。另外,查看此答案以获取详细示例:如何使用JSP/Servlet上传文件到服务器? 噢,请删除Netbeans生成的processRequest()方法。它绝对不是将doGet()doPost()委托给单个processRequest()方法的正确方式,这只会让其他不使用Netbeans的开发人员和维护人员感到困惑。

非常感谢你!终于可以正常工作了...现在我可以带着微笑去健身房了!附言:我已经摒弃了processRequest()函数。 - Ohadza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接