简体   繁体   English

将图像从android上传到java servlet并保存

[英]Upload image from android to java servlet and save it

I've been looking all over for this and nothing worked for me. 我一直在寻找这个,没有什么对我有用。

I'm trying to upload an image from android app to java servlet and save it in the server. 我正在尝试将图像从Android应用程序上传到java servlet并将其保存在服务器中。 Every solution I found didn't work for me. 我找到的每个解决方案都不适用于我。

What my code currently does: the android app is sending the image to the servlet, when i'm trying to save it the file is created, but it's empty :( 我的代码目前做了什么:android应用程序将图像发送到servlet,当我试图保存它时,文件被创建,但它是空的:(

Thanks for your help! 谢谢你的帮助!

My code in the android client (i_file is the file location on the device): 我在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();

}

My code in the server side: 我在服务器端的代码:

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 code: 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;
}

You misinterpreted the problem. 你误解了这个问题。 The image file is not empty, but the image file is corrupted because you're storing the entire HTTP multipart request body as an image file instead of extracting the part containing the image from the HTTP multipart request body. 图像文件不为空,但图像文件已损坏,因为您将整个HTTP多部分请求主体存储为图像文件,而不是从HTTP多部分请求主体中提取包含该图像的部分。

You need HttpServletRequest#getPart() to obtain the parts of a multipart request body. 您需要HttpServletRequest#getPart()来获取多部分请求主体的各个部分。 If you're already on Servlet 3.0 (Tomcat 7, Glassfish 3, etc), first annotate your servlet with @MultipartConfig 如果您已经使用Servlet 3.0(Tomcat 7,Glassfish 3等),请首先使用@MultipartConfig注释您的servlet

@WebServlet("/GetPictureFromClient")
@MultipartConfig
public class GetPictureFromClient extends HttpServlet {
    // ...
}

then fix your doPost() as follows to grab the part by its name and then its body as input stream: 然后按如下方式修复你的doPost() ,按名称抓取零件,然后将它的主体作为输入流:

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

If you're still not on Servlet 3.0 yet, then grab Apache Commons FileUpload . 如果你还没有使用Servlet 3.0,那么就抓住Apache Commons FileUpload See also this answer for a detailed example: How to upload files to server using JSP/Servlet? 有关详细示例,请参阅此答案: 如何使用JSP / Servlet将文件上载到服务器?

Oh, please get rid of the Netbeans-generated processRequest() method. 哦,请摆脱Netbeans生成的processRequest()方法。 It's absolutely not the right way to delegate both doGet() and doPost() to a single processRequest() method and it'll only confuse other developers and maintainers who don't use Netbeans. doGet()doPost()委托给单个processRequest()方法绝对不是正确的方法,它只会混淆不使用Netbeans的其他开发人员和维护人员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM