我有一个html文件中有一个dropbox和一个input,对应的有一个js控制dropbox中的onchange,我现在需要已经能够拖拽上传图片了,但是上传的图片内容在dropbox里面,可以用alert读出来图片名字,大小等信息,这个文件叫file。但是不知道怎么把这个文件赋值给input,因为上传的功能是绑定在input上的。困扰很久了QAQ
<textarea id="dropBox" onchange="processFiles(this.files)" readonly style="color: coral;font-family: 宋体,serif;font-size: large;text-align: center;line-height:100px">请拖拽上传图片~~
</textarea>
<input type="file" accept="image/*" id="submit_img" name="submit_img" style="background-color: #FaFaFa"/>
<script>
function processFiles(files) {
var file = files[0];
alert(file.value)
alert(file.name)
alert(file.size)
input.value=file.value
var output = document.getElementById("fileOutput");
//创建FileReader
var reader = new FileReader();
//告诉它在准备好数据之后做什么
reader.onload = function (e) {
//使用图像URL来绘制dropBox的背景
dropBox.style.backgroundImage = "url('" + e.target.result + "')";
dropBox.style.backgroundSize = "contain";
document.getElementById("dropBox").value="";
// var img_value = document.getElementById("dropBox");
};
//读取图片
reader.readAsDataURL(file);
}
<script>
function processFiles(files) {
// 获取上传的文件内容
const file = files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
// 将文件内容赋值给input file
const submitImg = document.getElementById('submit_img');
submitImg.value = reader.result;
}
}
在以上代码中,processFiles
函数会在用户上传文件后被调用。它首先从files
数组中获取上传的文件对象,然后创建一个FileReader
对象,并使用它读取文件内容。一旦读取完成,reader.onload
方法会被调用,其中reader.result
属性就是文件的内容。最后,我们将文件内容赋值给了submit_img
元素的value
属性,这样就可以将上传的文件作为表单数据一起提交到服务器了。
你试试这样能行不