How to resolve the C:\fakepath?

后端 未结 13 1726
梦如初夏
梦如初夏 2020-11-21 13:34

This is my upload button.



        
13条回答
  •  执念已碎
    2020-11-21 14:05

    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!

    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!

    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...

    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.

    // 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  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 
    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 fileUnderlay.text(filePath); // clear the timer var clearTimeout(ieBugTimeout); }, 10); }); } }); })(jQuery);

提交回复
热议问题