title: How to send .jpg as HTTP through a TcpStream?
body: <p>I tried to write a static HTTP file server, but I'm stuck when I try to send a <code>.jpg</code> file through <code>TcpStream</code>.</p>
  
  <p>Even if I <code>read</code> the file as binary, the browser doesn't seem to be able to decode the image:</p>
  
  <pre><code>extern crate chunked_transfer;
  use std::net::{TcpListener, TcpStream};
  use std::io::{Read, Write};
  use std::thread;
  use std::fs::File;
  use chunked_transfer::Encoder;
  
  fn main() {
      let listener = TcpListener::bind("127.0.0.1:9527").unwrap();
      println!("Listening for connections on port {}", 9527);
      for stream in listener.incoming() {
          match stream {
              Ok(stream) =&gt; {
                  thread::spawn(|| handle_client(stream));
              }
              Err(e) =&gt; println!("Unable to connect: {}", e),
          }
      }
  }
  
  fn get_path(mut stream: &amp;TcpStream) -&gt; String {
      let mut buf = [0u8; 4096];
      match stream.read(&amp;mut buf) {
          Ok(_) =&gt; {
              let req_str = String::from_utf8_lossy(&amp;buf);
              let path: Vec&lt;&amp;str&gt; = req_str.lines().next().unwrap().split(" ").collect();
              println!("GET {}", path[1]);
              // println!("{}", req_str);
              path[1].to_string()
          }
          Err(e) =&gt; {
              println!("Unable to read stream: {}", e);
              "/".to_string()
          }
      }
  }
  
  fn response(path: &amp;str, mut stream: TcpStream) {
      let file_path: &amp;str = &amp;("/home/xinbg/Downloads/wallpaper".to_string() + path);
      println!("{}", file_path);
      let mut buf = vec![0u8];
      let file = File::open(file_path);
      file.unwrap().read_to_end(&amp;mut buf);
  
      let mut encoded: Vec&lt;u8&gt; = vec![];
      {
          let mut encoder = Encoder::with_chunks_size(&amp;mut encoded, 8);
          encoder.write_all(&amp;buf);
      }
  
      let headers =
          ["HTTP/1.1 200 OK", "Content-type: image/jpeg", "Transfer-Encoding: chunked", "\r\n"];
      let mut response: Vec&lt;u8&gt; = headers.join("\r\n")
          .to_string()
          .into_bytes();
      response.extend(encoded);
  
      match stream.write(&amp;response) {
          Ok(_) =&gt; println!("Response sent"),
          Err(e) =&gt; println!("Failed sending response: {}", e),
      }
  }
  
  fn handle_client(stream: TcpStream) {
      response(&amp;get_path(&amp;stream), stream);
  }
  </code></pre>
  
  <p>I heard that there is some kind of "HTTP server standard guide book" stuff, any idea where to find it?</p>