gpt4 book ai didi

java - 将图像发送到浏览器客户端

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:29 30 4
gpt4 key购买 nike

我正在 Android 上开发一个网络服务器,但无法将二进制文件发送到浏览器。提前致谢

how do I send binary data to browser. Please, do it using outputstream and inputstream.

Socket soc=server.accept();
BufferedReader buff=new BufferedReader(new InputStreamReader(soc.getInputStream()));

try{
String req=buff.readLine().replace(" HTTP/1.0","").replace(" HTTP/1.1","").replace("GET ","");
//setTitle(req);
//buff.close();
File f=new File(homedir+req);
if(f.isDirectory()){
File f2=new File(homedir+req+"/index.html");
File f3=new File(homedir+req+"/INDEX.html");
if(f2.exists()||f3.exists()){
try{
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
pw.print("HTTP/1.0 200 OK\n\rContent-type: text/html\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f2);
copyStream(inst,out);
out.close();
pw.close();
}catch(Exception k){
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
pw.print("HTTP/1.0 200 OK\n\rContent-type: text/html\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f3);
copyStream(inst,out);
inst.close();
out.close();
pw.close();
}
}else
throw new Exception("file not found");
}else{
OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
String mim="";
try{
mim=MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));
}catch(Exception k){
mim="text/html";
}
if(mim.isEmpty()){
mim="text/html";
}
pw.print("HTTP/1.0 200 OK\n\rContent-type: "+mim+"\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f);
copyStream(inst,out);
inst.close();
out.close();
pw.close();
}
}catch(Exception k){
PrintWriter pw=new PrintWriter(soc.getOutputStream());
pw.print("<html><h1>"+k.getMessage()+"</h1></html>");
pw.flush();
pw.close();
}
buff.close();
soc.close();

The browser shows the following when this is called:

OutputStream out=soc.getOutputStream();
PrintWriter pw=new PrintWriter(out);
String mim="";
try{
mim=MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));
}catch(Exception k){
mim="text/html";
}
if(mim.isEmpty()){
mim="text/html";
}
pw.print("HTTP/1.0 200 OK\n\rContent-type: "+mim+"\n\r\n\r");
pw.flush();
//pw.close();
FileInputStream inst=new FileInputStream(f);
copyStream(inst,out);
inst.close();
out.close();
pw.close();

浏览器显示的内容如下:

What the browser shows

最佳答案

此处更改:

String mim="image/"

try{
mim += MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.getName().substring(f.getName().lastIndexOf(".")+1));

此代码为图像设置正确的内容类型,例如:

image/jpg
image/jpeg
image/png

关于java - 将图像发送到浏览器客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40101964/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com