java Servelet to pass binary data

Posted in :

如何在 java servlet 中, 輸出 binary data.

File f = new File("C:\\test.gif");
byte data[] = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new java.io.FileInputStream(f));
in.readFully(data);
in.close();
resp.setContentType("image/gif");

ServletOutputStream o = resp.getOutputStream();
o.write(data);
o.flush();
o.close();

輸出 zip 用的 header 有這幾個,

  • application/x-gzip
  • application/x-gtar
  • application/x-tar
  • application/zip

輸出 zip 的java 範例:

 public class GZIPEncodingServlet extends HttpServlet {...}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (req.getHeader("Accept-Encoding").contains("gzip")) {

        // 'try' block need for closing of stream, of course we can use 'close()' method for our 'PrintWriter' too
        try (PrintWriter printWriter = new PrintWriter(new GZIPOutputStream(resp.getOutputStream()))) {

            resp.setHeader("Content-Encoding", "gzip"); // Client must understood what we're sending him
            printWriter.write("Hello world from gzip encoded html"); // What is sending?
        }

    } else {
        resp.getWriter().write("Can't encode html to gzip :(");
    }

}

範例2號: Sending and receiving binary data in Servlets
https://stackoverflow.com/questions/5180375/sending-and-receiving-binary-data-in-servlets

InputStream is=request.getInputStream();
OutputStream os=response.getOutputStream();
byte[] buf = new byte[1000];
for (int nChunk = is.read(buf); nChunk!=-1; nChunk = is.read(buf))
{
    os.write(buf, 0, nChunk);
} 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *