<input type="file" id="file-id" name="file_name" onchange="theimage();">

这是我的上传按钮。

<input type="text" name="file_path" id="file-path">

这是一个文本字段,我必须在其中显示文件的完整路径。

function theimage(){
 var filename = document.getElementById('file-id').value;
 document.getElementById('file-path').value = filename;
 alert(filename);
}

这是解决我的问题的JavaScript。但在警报值给我

C:\fakepath\test.csv 

Mozilla给了我:

test.csv

但我想要本地完全限定文件路径。如何解决这个问题?

如果这是由于浏览器安全问题,那么应该采取什么替代方法来做到这一点?


一些浏览器具有安全特性,可以防止JavaScript知道文件的本地完整路径。这是有道理的——作为客户端,您不希望服务器知道您本地机器的文件系统。如果所有浏览器都这样做就太好了。

如果你真的需要发送上传文件的完整路径,那么你可能不得不使用一些类似于signed java applet的东西,因为如果浏览器不发送它,就没有任何方法获得这些信息。

我也遇到了同样的问题。在IE8中,可以通过在文件输入控件后创建一个隐藏输入来解决这个问题。用它的前一个兄弟的值填充这个。在IE9中这个问题也被修复了。

我想要了解完整路径的原因是在上传之前创建一个javascript图像预览。现在我必须上传文件来创建所选图像的预览。

如果你打开ie,工具,Internet选项,安全,自定义,找到“当上传文件到服务器时包括本地目录路径”(这是相当低的方法),然后点击“启用”。这是可行的

我很高兴浏览器能把我们从侵入性脚本和类似的东西中拯救出来。我不喜欢IE把一些东西放进浏览器,使一个简单的风格修复看起来像黑客攻击!

我使用了< span >来表示文件输入,这样我就可以对< div >而不是< input >应用适当的样式(同样,因为IE)。现在,由于这个IE想要向用户显示一个具有值的路径,这只是保证让他们保持警惕和在最不担心(如果没有完全吓退他们?!)…更多的IE-CRAP !

无论如何,感谢那些在这里发布解释的人:IE浏览器安全:在输入[type="file"]中添加"fakepath"到文件路径,我已经把一个小的修复器放在一起…

下面的代码做了两件事——它修复了lte 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);

我使用对象FileReader的输入onchange事件为您的输入文件类型!本例使用readAsDataURL函数,因此您应该有一个标记。FileReader对象还具有readAsBinaryString来获取二进制数据,稍后可以使用这些数据在服务器上创建相同的文件

例子:

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;
}

似乎你不能在你的localhost通过js找到完整的路径,但你可以隐藏fakepath只是显示文件名。使用jQuery获取文件输入的选择的文件名而不包含路径

Use

document.getElementById("file-id").files[0].name; 

而不是

document.getElementById('file-id').value

Hy那里,在我的情况下,我使用asp.net开发环境,所以我想在异步ajax请求上传这些数据,在[webMethod]你不能捕捉文件上传器,因为它不是静态元素, 所以我不得不通过固定路径来解决这个问题,而不是将想要的图像转换为字节以保存在DB中。

这是我的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;
             }
         }

这里仅供测试:

 $(document).ready(function () {
             FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
         });
// this will give you : ~/EnsaLmadiLiYghiz

使用文件阅读器:

$(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 + ")" });

        }
    }

在Chrome/Chromium的应用程序,如electron,你可以只使用target.files:

(我在这个例子中使用React JS)

const onChange = (event) => {
  const value = event.target.value;

  // this will return C:\fakepath\somefile.ext
  console.log(value);

  const files = event.target.files;

  //this will return an ARRAY of File object
  console.log(files);
}

return (
 <input type="file" onChange={onChange} />
)

我上面所说的File对象看起来是这样的:

{
  fullName: "C:\Users\myname\Downloads\somefile.ext"
  lastModified: 1593086858659
  lastModifiedDate: (the date)
  name: "somefile.ext"
  size: 10235546
  type: ""
  webkitRelativePath: ""
}

如果你想获取路径,你可以获取fullName。

注意,这只适用于chrome/chromium浏览器,所以如果你不需要支持其他浏览器(比如你正在构建一个电子项目),你可以使用这个。

您至少可以在您的机器上获得文件路径的临时创建副本。这里唯一的条件是输入元素应该在表单中 你必须做的其他事情是在表单中放入一个属性enctype,例如:

<form id="formid" enctype="multipart/form-data" method="post" action="{{url('/add_a_note' )}}">...</form>

你可以在底部找到路径字符串。 它打开流文件,然后删除它。

我发现,最好的解决方案是使用像Multer这样的中间件。下面是一个简短的概述:

npm i multer Add enctype="multipart/form-data" to your html form. In your backend dock where you're making your post request, require multer (const multer = require('multer')) In the same dock, set your upload destination: const upload = multer({dest:'uploas/'}). This will automatically create a local folder called 'uploads' where your files will be added. The code I've included shows you how to upload to your local disk storage. If you're using cloud storage (e.g. AWS, Azure, Cloudinary etc.) you can check out the Multer docs to see how to manage that. There aren't too many extra steps though. in your post request, add 'upload.single' (for one file) or 'upload.array' (for multiple files), like this:

路由器。Post ('/new', upload.single('image'), async function(req, res) {//'image'应该是你在req.body中发送的输入的名称 Console.log (req.file) //注意,如果你使用的是'upload. log '。数组',这个应该是'req。files' });

要求的事情。文件将有一个完整的路径名称,您可以在您的post请求中使用。欲了解更多信息,请查看Multer文档:

https://www.npmjs.com/package/multer

我希望这能有所帮助!