将本地文件发布为http请求

发布时间 2023-05-05 14:14:22作者: 骑驴晒太阳
@PostConstruct
public void init()
{
  //发布端口 8000
InetSocketAddress address = new InetSocketAddress(8000);
   try {    
     HttpServer httpServer = HttpServer.create(address, 1);
         httpServer.createContext("/", (context)->{
      //文件存储路径-----
D:/important/images/
String filePath = "D:/important/images/"+context.getRequestURI().toString();
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
context.sendResponseHeaders(200,bytes.length);
context.getResponseHeaders().add("content-type","image/*");
context.getResponseBody().write(bytes);
context.close();
});
httpServer.start();
} catch (IOException e) {

}
}