I have few images that I want to upload to my server. The client side is written in Java, and I will be making a HTTP Post request to upload images. Do I need to write server side code to handle the http post request? If so, where can I find some examples? The server supports PHP and Tomcat.

Comments

PHP Reference: php.net/manual/en/features.file-upload.php you may want to add some more detail, though - you are not saying what you are planning to do with the uploads, and whether any kind of authentication is necessary

Written by Pekka

This will help stackoverflow.com/questions/1067655/…

Written by Jigar Joshi

@pekka I have an Android app and I'm uploading the user's images to my server, so they can view them online. All images will be stored in public folder. The server is not behind any authentication at the moment.

Written by user558565

Accepted Answer

It is very simple to implement in java. You have to implement HTTP servlet that overrrides doPost() method that reads from input stream obtained from HTTP request and writes to file output stream.

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream in = req.getInputStream();
    OutputStream out = new FileOutputStream("myfile.jpg");
    IOUtils.copy(in, out);
    out.flush();
    out.close();
}

IOUtils is a utility calss from jakarta commons. If you do not want to include this library into your class path here is the source code of copy() method:

protected 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;
}
Written by AlexR
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki