Html 如何在网页中显示本地图片?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4908171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show local picture in web page?
提问by Artem
I need to show a picture on web page without uploading it. something like
我需要在网页上显示图片而不上传它。就像是
<img id="RuPic" src="file://localhost/D:/folder/image.jpg"/>
How to do that?
怎么做?
回答by Marcelo Lazaroni
You can do that easily using FileReader.readAsDataURL()
. The user chooses an image and you can display it without needing to upload it.
您可以使用FileReader.readAsDataURL()
. 用户选择一张图片,您无需上传即可显示。
For more info see https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
Here is the code:
这是代码:
function previewFile() {
// Where you will display your image
var preview = document.querySelector('img');
// The button where the user chooses the local image to display
var file = document.querySelector('input[type=file]').files[0];
// FileReader instance
var reader = new FileReader();
// When the image is loaded we will set it as source of
// our img tag
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
// Load image as a base64 encoded URI
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
回答by Pekka
Linking to local image files from remote HTML files used to be possible, but no longer is.
从远程 HTML 文件链接到本地图像文件曾经是可能的,但现在不再可能。
In Firefox since version 1.5 (background and config options here)
In Internet Explorer I thinksince Version 8 (I believe I have successfully done this in IE 7, but I can't find hard data)
In Chrome probably since forever
在 Firefox 1.5 版本后(背景和配置选项在这里)
在 Internet Explorer 中,我认为从版本 8 开始(我相信我已经在 IE 7 中成功完成了此操作,但是我找不到硬数据)
在 Chrome 中可能永远
See for example this vulnerability reportfor why this is a good thing.
例如,请参阅此漏洞报告,了解为什么这是一件好事。
I don't think there is a workaround. You will just have to upload the image first.
我不认为有解决方法。您只需要先上传图像。
回答by ConductedClever
You must make a way to answer file requests and move your files near your project source. then make your addressing relative. This is my code which works fine for me:
您必须设法回答文件请求并将文件移动到项目源附近。然后让你的地址成为亲戚。这是我的代码,对我来说很好用:
package ir.cclever.example;
import java.awt.List;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WellCloseWebServer {
public class clientInfo{
public String ip;
public Date visitTime;
}
static ArrayList<clientInfo> clients = new ArrayList<clientInfo>();
public void start() throws IOException {
ServerSocket listener = new ServerSocket(8181,1000);
System.out.println("Webserver starting up on port 8181");
System.out.println("Waiting for connection");
//==========================regex
String pathRegex = "(?<=GET /).+?(?= HTTP)";
Pattern pathPattern = Pattern.compile(pathRegex);
//==========================/regex
try {
while (true) {
Socket socket = listener.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String wholeRequest = "";
String line;
String requestHeaders = in.readLine();
wholeRequest = wholeRequest.concat(requestHeaders + "\n<br>");
while(!(line = in.readLine()).equals("")){
wholeRequest = wholeRequest.concat(line + "\n<br>");
}
wholeRequest = wholeRequest.concat("\n<br/>\n<br/>\nClient IP Address : " + socket.getRemoteSocketAddress().toString());
wholeRequest = wholeRequest.concat("\n<br/>\n<br/>\nClient Opened Port : " + ((Integer)socket.getPort()).toString());
clientInfo newClient = new clientInfo();
newClient.ip = socket.getRemoteSocketAddress().toString();
newClient.visitTime = new Date();
clients.add(newClient);
Matcher pathMatcher = pathPattern.matcher(requestHeaders);
Boolean anyPath = pathMatcher.find();
System.out.println("Connection, sending data to request : " + requestHeaders);
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
if (!anyPath) {
JustHello(out);
}
else {
String directory = pathMatcher.group();
System.out.println(directory);
if (directory.toString().equals("pic")) {
JustPic(out);
}
else if(directory.toString().startsWith("server/")){
getFile(directory,dos,true);
}
else if(directory.toString().endsWith("jpg")){
getFile(directory,dos,false);
}
else if(directory.toString().equals("my.aspx")){
mirror(out,wholeRequest);
}
else if(directory.toString().equals("clients.html")){
WholeClients(out);
}
else{
errorPage(out);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
private void InvalidRequestMethod(PrintWriter out, String string) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 404 NOT FOUND");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>Just GET</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\nInvalid request mehtod! : "+ string +"\n</body>\n</html>");
out.flush();
}
private void errorPage(PrintWriter out) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 404 NOT FOUND");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>Error 404 NOT FOUND!</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\nContent not found on server!\n</body>\n</html>");
out.flush();
}
private void WholeClients(PrintWriter out) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>Whole Clients</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\n");
Integer i=0;
for (clientInfo item : clients) {
i++;
out.print("<br/>\n"+i.toString()+") ip : " + item.ip + " | visit time : " + item.visitTime.toString());
}
out.print("\n</body>\n</html>");
out.flush();
}
private void mirror(PrintWriter out, String requestHeaders) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>My Info</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\n" +
requestHeaders.toString() +
"\n</body>\n</html>");
out.flush();
}
private void getFile(String directory, DataOutputStream os, boolean b) {
String CRLF = "\r\n";
// Open the requested file.
String fileName = directory;
FileInputStream fis = null;
boolean fileExists = true;
try {
//(new File(fileName)).mkdirs();
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "200 OK" + CRLF;
contentTypeLine = "Content-type: " +
contentType( fileName ) + CRLF;
} else {
statusLine = "404 NOT FOUND" + CRLF;
contentTypeLine = "Content Not Found!" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
// Send the status line.
try {
if (b) {
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
}
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes("File DNE: Content Not Found!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
return "image/jpeg";
}
if(fileName.endsWith(".gif")) {
return "image/gif";
}
if(fileName.endsWith(".png")) {
return "image/png";
}
if(fileName.endsWith(".js")) {
return "text/javascript";
}
if(fileName.endsWith(".css")) {
return "text/stylesheet";
}
return "application/octet-stream";
}
private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 ) {
os.write(buffer, 0, bytes);
}
}
private void JustHello(PrintWriter out) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>Just Hello</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\nHello World\n</body>\n</html>");
out.flush();
}
private void JustPic(PrintWriter out) {
// TODO Auto-generated method stub
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: Bot");
// this blank line signals the end of the headers
out.println("");
out.flush();
// Send the HTML page
out.print("<!DOCTYPE html>\n<html>\n<head>\n<title>Just Pic</title>\n<meta charset=\"UTF-8\">\n</head>\n<body>\n<img src=\"/images/th.jpg\"/>\n</body>\n</html>");
out.flush();
}
}
see the if clause that responds to the requests that start with /server. the follow the code to where it handles the request. it returns the files as a file transporter. so the address here "server/image.jpg" will be a address that you give in regular programming in java. this address is from the root of your project. mention that this code must have a main to use the class. this works perfect for me.
请参阅响应以 /server 开头的请求的 if 子句。按照代码处理请求。它将文件作为文件传输器返回。所以这里的地址“server/image.jpg”将是你在java常规编程中给出的地址。这个地址来自你的项目的根。提到此代码必须有一个 main 才能使用该类。这对我来说很完美。
回答by Luiz Jampolsky
I was looking for one answer and every where I found impossible, but i got the answer here:
我一直在寻找一个答案以及所有我发现不可能的地方,但我在这里得到了答案:
https://superuser.com/questions/224500/how-to-display-local-images-in-chrome-using-file-protocol
https://superuser.com/questions/224500/how-to-display-local-images-in-chrome-using-file-protocol
works very good on chrome .
在 chrome 上效果很好。
回答by anroesti
Okay, you can't just let somebody else acess your local file system! You would need a server-service like Apache, let your computer run 24h a day, make sure it wont overheat, care for good security and much more to make that even possible. And because server-administration is expensive and time-consuming, most people let the pro's host our stuff for us (Webhosting).
好的,您不能让其他人访问您的本地文件系统!你需要一个像 Apache 这样的服务器服务,让你的计算机一天 24 小时运行,确保它不会过热,关心良好的安全性等等,以使其成为可能。而且由于服务器管理既昂贵又耗时,大多数人让专业人士为我们托管我们的东西(Webhosting)。
In conclusion, if you don't want to run your own server, it's much easier to just upload it to your webhoster of choice.
总之,如果您不想运行自己的服务器,只需将其上传到您选择的网络托管服务商就容易多了。