简体   繁体   中英

Input tag type file

How to import file to the input tag (default.jpeg for example) if user does not select the file, I want to get the file from the input tag in JS and pass it to the server then get it and load. Now It works, but I can only get the file when user select itself, but when user does not select the file, I got error on the server, because the method want the file and that is why I want to load the default file to the input tag before user select any.

做这个:

document.querySelector("input[type='file']").value = "default.jpeg";

You can't.

The only way to set the value of a file input is by the user to select a file.

This is done for security reasons. Otherwise, you would be able to create a Javascript that automatically uploads a specific file from the client's computer.

But if you want to do it forcefully you can do it like that.

<!DOCTYPE html>
<html>
<body>

Name: <input type="file" id="myText" value="Mickey">

<p>Click the button to display the default value of the text field.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myText").defaultValue="default.jpeg";
    document.getElementById("demo").innerHTML = x;

}
</script>

</body>
</html>

Hope it will help you in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM