daniegarcia254
daniegarcia254

Reputation: 1207

Serve gif image from http server, not displaying ok in the browser

I've built a simple concurrent web server with TCP sockets in Java. It works fine serving html, txt, css, etc... content but I'm having problems serving image files (gif in this case).

I think the process is ok, because the browser gets the image with a 200 OK Status and data (path, file size, etc...) is also ok; but I'm not able to accomplish that the browser shows the image, it always shows an empty image with the alternative text. Path of the images is also ok.

I've tried differents methods of serve the image to the client, none of them has worked for me so far.

This is the code I use for serve an image/gif:

       out = new PrintWriter(client.getOutputStream());

       httpHeader= (h+" 200 OK \n" +
                            "Content-Type: image/gif"+"\n" +
                            "Content-Length: "+f.length()+"\n\n");
                    //Send header to the client
                    out.println(httpHeader);
                    out.flush();
                    //Send gif file content to the cliente
                    returnGIF(f);


    private void returnGIF(File f) throws IOException{
        FileInputStream fis = new FileInputStream(f.getPath());
        int b=0;
        while ((b=fis.read()) != -1){
            out_bis.write(b);
        }
        fis.close();
    }

Upvotes: 0

Views: 1377

Answers (2)

SomeRandomName
SomeRandomName

Reputation: 603

Try Adding responseType:'arraybuffer' to the header. So the browser can interprit the files correctly.

Upvotes: 1

Jerry101
Jerry101

Reputation: 13407

An HTTP header needs to have \r\n line terminators, not \n. Furthermore since the variable httpHeader includes newlines (albeit the wrong kind of newlines), you should print it to the stream by calling print(), not println() which appends another newline.

It'd be prudent to flush the GIF data after writing it.

There might be more problems.

(BTW, writing the GIF data a byte array at a time would be much faster.)

Upvotes: 2

Related Questions