开发者

Upload Images to Server

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开发者_Go百科 to handle the http post request? If so, where can I find some examples? The server supports PHP and Tomcat.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜