- Как создать ссылку на локальный файл на локально запущенной веб-странице?
- 5 ответов:
- почему он застревает без file:/// ?
- почему в три раза?
- эти файлы по-прежнему открываются в браузере и это хорошо
- html/javascript link to a local file
- 3 Answers 3
- What are the ways to make an html link open a folder
- 9 Answers 9
- How to specify a local file within html using the file: scheme?
- 5 Answers 5
- How can I create a link to a local file on a locally-run web page?
- 5 Answers 5
- You cannot cross from http(s) to the file protocol
- Why does it get stuck without file:/// ?
- Why three slashes?
- These files will still open in your browser and that is good
Как создать ссылку на локальный файл на локально запущенной веб-странице?
Я хотел бы иметь html-файл, который организует определенные файлы, разбросанные по всему моему жесткому диску. Например, у меня есть два файла, на которые я бы ссылался:
проблема в том, что я хотел бы, чтобы ссылки функционировали как ярлык для файла. Я пробовал следующее:
. но первая ссылка ничего не делает, а вторая ссылка открывает файл в Chrome, а не VLC.
мои вопросы являются:
есть ли способ настроить мой HTML для обработки ссылок в качестве ярлыков для файлов?
Если нет способа настроить HTML, есть ли другие способы аккуратно связать файлы, разбросанные по всему жесткому диску?
Мой компьютер работает под управлением Windows 7 и мой веб-браузер Chrome.
5 ответов:
вы должны использовать file:/// протокол (да, это три косые черты), если вы хотите связать с локальными файлами.
они никогда не откроют файл в ваших локальных приложениях автоматически. это из соображений безопасности, и я доберусь до этого в последнем разделе. Если он откроется, он будет открыт только в браузере. Если это ваш браузер может отображать файл, он будет. Если он не может, он, вероятно, спросит вас, Хотите ли вы его загрузить.
некоторые браузеры, такие как современные версии Chrome, даже откажутся переходить из протокола http в протокол file, поэтому вам лучше убедиться, что вы открываете это локально, используя протокол file, если вы хотите сделать это вообще.
почему он застревает без file:/// ?
первая часть URL — это протокол. Протокол — это несколько букв, затем двоеточие и две косые черты. HTTP:// и FTP:// действительны протоколов; C:/ нет, и я уверен, что это даже толком не похож на него.
C:/ также не является допустимым веб-адресом. Браузер может предположить, что это должно быть http://c/ С указанным пустым портом, но это не сработает.
Ваш браузер может не предполагать, что он ссылается на локальный файл. У него мало оснований для такого предположения, потому что публичные сайты обычно не пытаются ссылаться на локальные файлы людей.
Итак, если вы хотите получить доступ к локальным файлам: скажите ему использовать файл протокол.
почему в три раза?
потому что это часть схема URI файла. У вас есть возможность указать хост после первых двух косых черт. Если вы пропустите указание хоста, он просто предположит, что вы ссылаетесь на файл на своем собственном ПК. Другими словами: file:///C:/etc ярлык для file://localhost/C:/etc .
эти файлы по-прежнему открываются в браузере и это хорошо
Ваш браузер будет реагировать на эти файлы точно так же они отвечают на один и тот же файл в любом месте в интернете. Эти файлы не будет откройте в своем обработчике файлов по умолчанию (например, MS Word или VLC Media Player), и вы не будет можно сделать что-нибудь вроде ask File Explorer, чтобы открыть местоположение файла.
это очень хорошая вещь для вашей безопасности.
сайты в браузере не может взаимодействовать с вашей операционной системой. Если бы хороший сайт мог сказать lecture. mp4 to open in VLC.exe, вредоносный сайт может сказать ему, чтобы открыть .летучая мышь in CMD.exe. Или он может просто сказать вашему компьютеру, чтобы запустить несколько удалить.exe файлы, или открыть файловый проводник миллион раз.
это может быть неудобно для вас, но HTML и безопасность браузера на самом деле не предназначены для того, что вы делаете. Если вы хотите иметь возможность открытьlecture. mp4 in VLC.exe, рассмотрите возможность написания настольного приложения вместо этого.
Если вы используете IIS на вашем компьютере, вы можете добавить каталог, который вы пытаетесь достичь в качестве виртуального каталога. Для этого вы щелкните правой кнопкой мыши на своем сайте в ISS и нажмите «Добавить виртуальный каталог». Назовите виртуальную папку. Наведите виртуальную папку в папку, расположенную на локальном компьютере. Вы также должны предоставить учетные данные, которые имеют привилегии для доступа к определенной папке, например. Имя хоста\имя пользователя и пароль. После этого вы можете получить доступ к файлу в виртуальной папке, как и к любому другому файлу ваш сайт.
кстати, это также работает с Chrome, который в противном случае не принимает файл-протокол file://
надеюсь, это кому-то поможет 🙂
а затем щелкните правой кнопкой мыши, выберите опцию «копировать местоположение», а затем вставьте в url.
У меня есть способ и работать так:
html/javascript link to a local file
I’m trying to show a link to a local file using javascript, and it isn’t working. I’m not sure what I’m doing wrong.
and the javascript is:
when I click on the content, it just shows a blank screen. I’ve tried to make the link every way I know how, and I’m sure I’m missing something silly, but it’s driving me crazy! I can’t even get my jquery .show to do any of it’s inputs like explode or puff, but if I use div elements with text and borders, it shows up. Please help! Thanks so much.
3 Answers 3
There are few corrections in your page:
And To Load Local scripts use: file:/// for it:
By Using file:/// and C:/ instead of C:// for all coz it is sites address and not javascript files address. Also You’re including JQuery correctly aright after that line using: . So first line is un-necessary and wrong. – Vedant Terkar Jun 4 ’14 at 17:45
If you’re running the script locally (via your browser’s File -> Open menu option) then you don’t need the drive letter, unless it’s on a different drive. If you want to use whatever path you want, use file:// in front. In other words, you can use file:// anywhere you could use http://.
Remember, all paths are relative to the script location.
When you do that the link will not download the file to your client, I suppose this is what you want.
If this page is going to be served over the internet, you should not be using URLs relative to your computer, instead relative to the server computer:
- I would search what is the folder that the web server is. serving :p. Which in your case seems to be: c:\wamp\www
- Try changing the link href to /Projects/tile/name.docx . This is the URL relative to the server, which means that when your user is in your page, for example: http://localhost , and clicks the link, user would try to go to: http://localhost/Projects/tile/name.docx .
- The server would search in its file system c:\wamp\www\Projects\tile\name.docx .
Note how the file system URLs c:\wamp\www\.. and URLs of the form http://localhost/. are different.
In this case you want in your page an URL of the form http://. , because if you use a file system URL when the person looking at your page clicks the link the browser would search the file in the person computer, and not in the server computer.
Also, you could want to remove c:/wamp/www/ in every place you have it and just leave / .
What are the ways to make an html link open a folder
I need to let users of an application open a folder by clicking a link inside a web page. The path of the folder is on the network and can be accessed from everywhere. I’m probably sure there is no easy way to do this, but maybe I’m mistaken?
9 Answers 9
Do you want to open a shared folder in Windows Explorer? You need to use a file: link, but there are caveats:
- Internet Explorer will work if the link is a converted UNC path ( file://server/share/folder/ ).
- Firefox will work if the link is in its own mangled form using five slashes ( file://///server/share/folder ) and the user has disabled the security restriction on file: links in a page served over HTTP. Thankfully IE also accepts the mangled link form.
- Opera, Safari and Chrome can not be convinced to open a file: link in a page served over HTTP.
The URL file://[servername]/[sharename] should open an explorer window to the shared folder on the network.
make sure your folder permissions are set so that a directory listing is allowed then just point your anchor to that folder using chmod 701 (that might be risky though) for example
make sure that you have no index.html any index file on that directory
Using file:///// just doesn’t work if security settings are set to even a moderate level.
If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the «A share located on another computer» is selected and the «Connect as. » is an account that can see the network location.
Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.
*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.
How to specify a local file within html using the file: scheme?
I’m loading a html file hosted on the OS X built in Apache server, within that file I am linking to another html file in the same directory as follows:
This works. However (for reasons too lengthy to go into) I am experimenting using the file: scheme instead, however I cannot get anything to work. Here is how I am re-writing the above line using file:
(192.168.1.57 is my current IP address)
Changing it to the following does also not work:
But the file cannot be found, how should it be specified using the file: scheme?
5 Answers 5
The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///
User/2ndFile.html . Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user’s path;
does no expand in a file: URL. So you would need file:///home/User/2ndFile.html (on most Unixes), file:///Users/User/2ndFile.html (on Mac OS X), or file:///C:/Users/User/2ndFile.html (on Windows).
Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file: URLs from other local pages.
The ‘file’ protocol is not a network protocol. Therefore file://192.168.1.57/
User/2ndFile.html simply does not make much sense.
Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way.
I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href=»2ndFile.html» simply works because it uses a «relative url». This makes the browser use the same protocol and path as where he got the first (current) file from.
the «file://» url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the «local machine» is the machine that is running the browser.
if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd and type hostname (example result: LAPTOP-G666P000 , you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E > right click ‘This PC’ > press N (It’s Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U: or G: or Z: or whatever you want Example Address: \\LAPTOP-G666P000\c$\Users\username\
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
How can I create a link to a local file on a locally-run web page?
I’d like to have an html file that organizes certain files scattered throughout my hard drive. For example, I have two files that I would link to:
The problem is that I’d like the links to function as a shortcut to the file. I’ve tried the following:
. but the first link does nothing and the second link opens the file in Chrome, not VLC.
My questions are:
Is there a way to adjust my HTML to treat the links as shortcuts to the files?
If there isn’t a way to adjust the HTML, are there any other ways to neatly link to files scattered throughout the hard drive?
My computer runs Windows 7 and my web browser is Chrome.
5 Answers 5
You need to use the file:/// protocol (yes, that’s three slashes) if you want to link to local files.
These will never open the file in your local applications automatically. That’s for security reasons which I’ll cover in the last section. If it opens, it will only ever open in the browser. If your browser can display the file, it will, otherwise it will probably ask you if you want to download the file.
You cannot cross from http(s) to the file protocol
Modern versions of many browsers (e.g. Firefox and Chrome) will refuse to cross from the http(s) protocol to the file protocol to prevent malicious behaviour.
This means a webpage hosted on a website somewhere will never be able to link to files on your hard drive. You’ll need to open your webpage locally using the file protocol if you want to do this stuff at all.
Why does it get stuck without file:/// ?
The first part of a URL is the protocol. A protocol is a few letters, then a colon and two slashes. HTTP:// and FTP:// are valid protocols; C:/ isn’t and I’m pretty sure it doesn’t even properly resemble one.
C:/ also isn’t a valid web address. The browser could assume it’s meant to be http://c/ with a blank port specified, but that’s going to fail.
Your browser may not assume it’s referring to a local file. It has little reason to make that assumption because webpages generally don’t try to link to peoples’ local files.
So if you want to access local files: tell it to use the file protocol.
Why three slashes?
Because it’s part of the File URI scheme. You have the option of specifying a host after the first two slashes. If you skip specifying a host it will just assume you’re referring to a file on your own PC. This means file:///C:/etc is a shortcut for file://localhost/C:/etc .
These files will still open in your browser and that is good
Your browser will respond to these files the same way they’d respond to the same file anywhere on the internet. These files will not open in your default file handler (e.g. MS Word or VLC Media Player), and you will not be able to do anything like ask File Explorer to open the file’s location.
This is an extremely good thing for your security.