Javascript 如何解决 C:\fakepath?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4851595/
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 resolve the C:\fakepath?
提问by e_maxm
<input type="file" id="file-id" name="file_name" onchange="theimage();">
This is my upload button.
这是我的上传按钮。
<input type="text" name="file_path" id="file-path">
This is the text field where I have to show the full path of the file.
这是我必须显示文件完整路径的文本字段。
function theimage(){
var filename = document.getElementById('file-id').value;
document.getElementById('file-path').value = filename;
alert(filename);
}
This is the JavaScript which solve my problem. But in the alert value gives me
这是解决我问题的 JavaScript。但在警报值给了我
C:\fakepath\test.csv
and Mozilla gives me:
Mozilla 给了我:
test.csv
But I want the local fully qualified file path. How to resolve this issue?
但我想要本地完全限定的文件路径。如何解决这个问题?
If this is due to browser security issue then what should be the alternate way to do this?
如果这是由于浏览器安全问题,那么执行此操作的替代方法应该是什么?
回答by Joe Enos
Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.
某些浏览器具有安全功能,可防止 JavaScript 知道您文件的本地完整路径。这是有道理的 - 作为客户端,您不希望服务器知道您本地机器的文件系统。如果所有浏览器都这样做就好了。
回答by Sardesh Sharma
Use
用
document.getElementById("file-id").files[0].name;
instead of
代替
document.getElementById('file-id').value
回答by chakroun yesser
I use the object FileReader on the input onchange
event for your input file type! This example uses the readAsDataURL function and for that reason you should have an tag. The FileReader object also has readAsBinaryString to get the binary data, which can later be used to create the same file on your server
我在输入onchange
事件上使用对象 FileReader作为您的输入文件类型!此示例使用 readAsDataURL 函数,因此您应该有一个标记。FileReader 对象也有 readAsBinaryString 来获取二进制数据,以后可以用来在你的服务器上创建相同的文件
Example:
例子:
var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
var img = document.getElementById("yourImgTag");
img.src = event.target.result;
}
回答by saikiran1043
If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work
如果您转到 Internet Explorer、工具、Internet 选项、安全性、自定义,找到“将文件上传到服务器时包括本地目录路径”(这是一段相当长的路),然后单击“启用”。这将工作
回答by Anand Sharma
I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!
我很高兴浏览器关心将我们从侵入性脚本等中拯救出来。我不满意 IE 在浏览器中放入一些东西,使简单的样式修复看起来像黑客攻击!
I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!
我使用了 <span> 来表示文件输入,以便我可以将适当的样式应用于 <div> 而不是 <input>(再次,因为 IE)。现在,由于这个 IE 想要向用户展示一个路径,该路径的值可以保证让他们保持警惕并且最不担心(如果不是完全吓跑他们?!)...更多 IE-CRAP!
Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...
无论如何,感谢在此处发布解释的人:IE 浏览器安全性:将“fakepath”附加到 input[type="file"] 中的文件路径,我已经整理了一个较小的修复程序 - 上...
The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.
下面的代码做了两件事 - 它修复了一个 IE8 错误,其中 onChange 事件在上传字段的 onBlur 之前不会触发,并且它使用不会吓到用户的清理过的文件路径更新元素。
// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
// document onReady wrapper
$().ready(function(){
// check for the nefarious IE
if($.browser.msie) {
// capture the file input fields
var fileInput = $('input[type="file"]');
// add presentational <span> tags "underneath" all file input fields for styling
fileInput.after(
$(document.createElement('span')).addClass('file-underlay')
);
// bind onClick to get the file-path and update the style <div>
fileInput.click(function(){
// need to capture $(this) because setTimeout() is on the
// Window keyword 'this' changes context in it
var fileContext = $(this);
// capture the timer as well as set setTimeout()
// we use setTimeout() because IE pauses timers when a file dialog opens
// in this manner we give ourselves a "pseudo-onChange" handler
var ieBugTimeout = setTimeout(function(){
// set vars
var filePath = fileContext.val(),
fileUnderlay = fileContext.siblings('.file-underlay');
// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
// update the file-path text using case-insensitive regex
filePath = filePath.replace(/C:\fakepath\/i, '');
}
// update the text in the file-underlay <span>
fileUnderlay.text(filePath);
// clear the timer var
clearTimeout(ieBugTimeout);
}, 10);
});
}
});
})(jQuery);
回答by Telefoontoestel
I came accross the same problem. In IE8 it could be worked-around by creating a hidden input after the file input control. The fill this with the value of it's previous sibling. In IE9 this has been fixed aswell.
我遇到了同样的问题。在 IE8 中,它可以通过在文件输入控件之后创建一个隐藏输入来解决。用它以前的兄弟的值填充它。在 IE9 中,这也已修复。
My reason in wanting to get to know the full path was to create an javascript image preview before uploading. Now I have to upload the file to create a preview of the selected image.
我想了解完整路径的原因是在上传之前创建一个 javascript 图像预览。现在我必须上传文件以创建所选图像的预览。
回答by jcoder
If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.
如果您真的需要发送上传文件的完整路径,那么您可能必须使用类似签名的 java 小程序之类的东西,因为如果浏览器不发送它,则没有任何方法可以获取此信息。
回答by Zernel
seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path
似乎您无法通过js在本地主机中找到完整路径,但是您可以隐藏假路径以仅显示文件名。使用 jQuery 获取文件输入的选定文件名而不带路径
回答by Marcos Di Paolo
Use file readers:
使用文件阅读器:
$(document).ready(function() {
$("#input-file").change(function() {
var length = this.files.length;
if (!length) {
return false;
}
useImage(this);
});
});
// Creating the function
function useImage(img) {
var file = img.files[0];
var imagefile = file.type;
var match = ["image/jpeg", "image/png", "image/jpg"];
if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
alert("Invalid File Extension");
} else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(img.files[0]);
}
function imageIsLoaded(e) {
$('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });
}
}
回答by Shiva Brahma
Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .
你好,就我而言,我使用的是 asp.net 开发环境,所以我想在异步 ajax 请求中上传这些数据,在 [webMethod] 中,您无法捕获文件上传器,因为它不是静态元素,所以我不得不通过修复路径来解决此类解决方案,而不是将想要的图像转换为字节以将其保存在数据库中。
Here is my javascript function , hope it helps you:
这是我的javascript函数,希望对你有帮助:
function FixPath(Path)
{
var HiddenPath = Path.toString();
alert(HiddenPath.indexOf("FakePath"));
if (HiddenPath.indexOf("FakePath") > 1)
{
var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
MainStringLength = HiddenPath.length - UnwantedLength;
var thisArray =[];
var i = 0;
var FinalString= "";
while (i < MainStringLength)
{
thisArray[i] = HiddenPath[UnwantedLength + i + 1];
i++;
}
var j = 0;
while (j < MainStringLength-1)
{
if (thisArray[j] != ",")
{
FinalString += thisArray[j];
}
j++;
}
FinalString = "~" + FinalString;
alert(FinalString);
return FinalString;
}
else
{
return HiddenPath;
}
}
here only for testing :
这里仅用于测试:
$(document).ready(function () {
FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
});
// this will give you : ~/EnsaLmadiLiYghiz