开发者

Getting value from <file> gives C:\fakepath\filename, even in Linux

开发者 https://www.devze.com 2023-03-15 15:56 出处:网络
I\'m getting some very strange behaviour from a file input element in both Chrome and Opera (possibly more, haven\'t tested).

I'm getting some very strange behaviour from a file input element in both Chrome and Opera (possibly more, haven't tested).

I have the following HTML:

<div id="profileImgContainer" class="formFile">
    <label>Profile Picture</label><div>
        <input type="text" id="profileImgText"><input type="button" value="Choose File" id="profileImgButton">
    </div>
    <input type="file" id="profileImg" name="profileImg">
</div>

And the following jQuery to get the file input's value and put it in the (visible) textbox. The actual file input is hidden.

$(".formFile input[type='file']").live('change', function()
{
    $(this).parents(".formFile").find("input[type='text']").val($(this).val());
});

I've made a JSFiddle for you try out. In Firefox, the text box happily takes the filename (don't care about the path) of the file element. In Chrome and Opera, however, when a file is selected开发者_如何学C the file path in the visible text box changes to C:\fakepath\[filename] where [filename] is the name of the file chosen. This path is obviously fake but what I want to know is why it's changed to it, and whether the file in the hidden upload element will still upload fine. I'm guessing it's a security feature, but I may be wrong.


This is one attempt to mitigate the security issues you get from allowing arbitrary foreign code to run in your browser: The script (which we assume could come from a malicious attacker) does not get to see (and possibly communicate back via AJAX) information about your local files.

Imagine what could happen if a script could just freely set file uploads and submit forms.

This behaviour concerning file upload controls and scripting is mandated by some sort of standard (I believe part of the DOM specification) for this very reason.


I just want to add a new answer for people facing this issue nowadays. Similar to one of the comments, it's better to use the input element itself. For example:

document.getElementById('file-input').files[0].path

This worked for me.

Similar solution for React:

const inpRef = useRef(null)

return (
<input type="file" onChange={() => { 
    const filePath = inpRef.current.files[0].path
    // You can use more properties by looking at the files object
 }} />
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号