Ori Popowski
Ori Popowski

Reputation: 10672

How to make the server download an image file that was uploaded in an HTTP PUT request from the client?

I need to implement a web server in Java. The web server should download image files that were uploaded by the clients in an HTTP PUT request. What is the procedure for doing it? What Java classes should I use?

Also, if you can recommend a good book that covers these topics it would be great. But the specific question is more important right now.

Upvotes: 0

Views: 663

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340993

You should read about Java servlets and servlet containers. Start by implementing a simple servlet that returns "Hello world" string.

Here is the shortest upload/download servlet ever:

import org.apache.commons.io.IOUtils;

@WebServlet(urlPatterns = {"/test"})
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        File f = new File("test.txt");
        resp.setContentLength((int) f.length());
        final FileInputStream input = new FileInputStream(f);
        IOUtils.copy(input, resp.getOutputStream());
        input.close();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final FileOutputStream output = new FileOutputStream("test.txt");
        IOUtils.copy(req.getInputStream(), output);
        output.close();
    }
}

First hit:

$ curl -X PUT -d "Hello, servlet" localhost:8080/test

To store given text in a file named test.txt somewhere on your disk. Then simply enter localhost:8080/test in your browser. I think it is a good start.

Upvotes: 2

Related Questions