如何获取输入类型=文件的值并将其显示在动态创建的图像上?

我有以下代码:


function displayImg() {

  let fileUpload = document.getElementById("fileUpload").value;

  let container document.getElementById("container");

  container.innerHTML = `<img src="fileUpload">`

  

}

<input type = file id = "fileUpload" accept = "image/*">

<button onclick = "displayImg()">Click to show</button>

<div id="container"></div>

我希望用户可以将文件输入到文件输入字段中,并在单击按钮时将其放入动态创建的图像的源中。我该怎么做呢?



炎炎设计
浏览 102回答 2
2回答

饮歌长啸

你可以试试这个<html><body><input type = file id = "fileUpload" accept = "image/*"><button onclick = "displayImg()">Click to show</button><div id="container"><img id="img"></div><script>function displayImg() {&nbsp; let fileUpload = document.getElementById("fileUpload").value;&nbsp; //alert(fileUpload);&nbsp; let image = document.getElementById("img");&nbsp; img.src = fileUpload;}</script></body></html>&nbsp;注意:该value属性仅返回文件名,因此图像应与代码位于同一文件夹中。或者,如果您愿意,可以在之前添加文件的路径。

侃侃尔雅

请使用以下代码:var uploadedFileURL;function handleFile() {&nbsp; var fileUploadControl = document.getElementById('fileUpload');&nbsp; var file = fileUploadControl.files[0];&nbsp; if (file) {&nbsp; &nbsp; var reader = new FileReader();&nbsp; &nbsp; reader.onload = function() {&nbsp; &nbsp; &nbsp; uploadedFileURL = reader.result;&nbsp; &nbsp; };&nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; }}function displayImg() {&nbsp; var fileUpload = document.getElementById("fileUpload").value;&nbsp; var container = document.getElementById("container");&nbsp; container.innerHTML = `<img src="${uploadedFileURL}">`;}<input id="fileUpload" type="file" onchange="handleFile()" accept="image/*" /><button onclick="displayImg()">Click to show</button><div id="container"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5