1. 程式人生 > >Jersey RESTful WebService框架學習(九)讀取圖片顯示

Jersey RESTful WebService框架學習(九)讀取圖片顯示

後端程式碼:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
@Path("/t")
public class ImageAPI {
	@Path("/images")
	@GET
	public void showImg(@PathParam("name") String imageName, @PathParam("type") String type,
			@Context HttpServletResponse response) throws IOException {
		InputStream inputStream = null;
		OutputStream out = null;
		try {
			File file = new File("D:\\t.png");
			inputStream = new FileInputStream(file);
			out = response.getOutputStream();
			// pic size = 1M
			byte[] bytes = new byte[1024 * 1024];
			int len = 0;
			while ((len = inputStream.read(bytes)) > 0) {
				out.write(bytes, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null)
				inputStream.close();
			if (out != null)
				out.close();
		}
	}
}


前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div>hello world</div>
	<img alt="" src="http://127.0.0.1:8080/Bank/api/1.0/t/images">
</body>
</html>