Sending a image to servlet in java how to get the image in servlet

不打扰是莪最后的温柔 提交于 2019-12-13 07:41:37

问题


I am sending a image from android phone to server which is a servlet I am using the HttpClient and HttpPost for this and ByteArrayBody for storing the image before sending.

how do i extract the image from the post request in Servlet.

Here is my code for sending the post request

String postURL = //server url;

HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(postURL);

ByteArrayBody bab = new ByteArrayBody(imageBytes,"file_name_ignored");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("source", bab);
postRequest.setEntity(reqEntity);

HttpResponse response = httpClient.execute(postRequest);

回答1:


Use something like commons fileupload.

There are examples in the Apache docs, and all over the web.




回答2:


Servlet 3.0 has support for reading multipart data. MutlipartConfig support in Servlet 3.0 If a servelt is annotated using @MutlipartConfig annotation, the container is responsible for making the Multipart parts available through

  1. HttpServletRequest.getParts()
  2. HttpServletRequest.getPart("name");



回答3:


use http://commons.apache.org/fileupload/using.html

private DiskFileItemFactory fif = new DiskFileItemFactory(); 

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if(!isMultipart)
        throw new ServletException("upload using multipart");

    ServletFileUpload upload = new ServletFileUpload(fif);
    upload.setSizeMax(1024 * 1024 * 10 /* 10 mb */);
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    if(items == null || items.size() == 0)
        throw new ServletException("No items uploaded");

    FileItem item = items.get(0);
    // do something with file item...
}


来源:https://stackoverflow.com/questions/7908886/sending-a-image-to-servlet-in-java-how-to-get-the-image-in-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!