1

I am using an Android client to post data and some file in Google cloud storage:

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
             entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
             entityBuilder.addBinaryBody("file", file);             
             entityBuilder.addTextBody("author", author);

On the server side I am using a servlet to get that request. However, while I am able to get the file and store it, I don't know how to get what's in the addTextBody (the "author" String in my case)

I have been searching for a while and just found someone that posted quite the same question but no one answered him. (How to get the text from a addTextBody in a miltipartentitybuilder)

Community
  • 1
  • 1
Kritias
  • 187
  • 1
  • 12

1 Answers1

4

Assuming you're using Servlet 3.0+, just use HttpServletRequest#getParts(). For example, if you wanted the content of the multipart part named author, you'd configure your servlet with @MultipartConfig, retrieve the appropriate Part object and consume its InputStream.

@MultipartConfig()
@WebServlet(urlPatterns = { "/upload" })
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            if (!part.getName().equals("author"))
                continue;
            try (InputStream in = part.getInputStream()){
                String content = CharStreams.toString(new InputStreamReader(in));
                System.out.println(content); // prints the value of author
            }
        }
    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724