简体   繁体   English

如何从div中的输入字段显示用户上传的图像文件

[英]How to show user uploaded image files from input field in a div

I have an input field of type file and whenever user uploads by clicking on that input, I want to show them the file they have selected, How can I do that using JS.我有一个文件类型的输入字段,每当用户通过单击该输入进行上传时,我想向他们展示他们选择的文件,我如何使用 JS 来做到这一点。

I have an input field of type file and whenever user uploads by clicking on that input, I want to show them the file they have selected, How can I do that using JS.我有一个文件类型的输入字段,每当用户通过单击该输入进行上传时,我想向他们展示他们选择的文件,我如何使用 JS 来做到这一点。 I don't know how to do it.我不知道该怎么做。

I think you want to get input as file form html form and display the image inside HTML div to show user which file they have selected.我认为您想以文件形式输入 html 形式并在 HTML div 中显示图像以向用户显示他们选择了哪个文件。

I have implement this in my project where user are allowed to upload image file hope this will help you.我在我的项目中实现了这个,允许用户上传图像文件希望这对你有所帮助。 You can use the onchange event of the input field to detect when a user has selected a file.您可以使用输入字段的 onchange 事件来检测用户何时选择了文件。 Then, you can use the files property of the input field to access the selected file(s).然后,您可以使用输入字段的文件属性来访问所选文件。 Here's an example:这是一个例子:

 <input type="file" id="file-input" onchange="showSelectedFile()">



function showSelectedFile() {
    var input = document.getElementById("file-input");
    var file = input.files[0];
    console.log(file.name); // Display the file name
 }

You can also use您也可以使用

URL.createObjectURL() URL.createObjectURL()

method to create a URL that can be used to refer to the file in a tag.创建一个 URL 的方法,它可以用来引用标签中的文件。

 var url = URL.createObjectURL(file);
 document.getElementById("img").src = url;

file.name will give the name of the selected file and URL.createObjectURL(file) will create a URL object for the selected file, this url can be used to set the source of an image tag. file.name 将给出所选文件的名称,而 URL.createObjectURL(file) 将为所选文件创建一个 URL object,此 url 可用于设置图像标签的来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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