Javascript 如何使用FormData对象获取文件名?
HTMLJavascript 如何使用FormData对象获取文件名?,javascript,form-data,Javascript,Form Data,HTML <form enctype="multipart/form-data" method="post" id='photo_details'> <input type="text" name="f_name"> <input type="file" accept="image/*" name="profile_pic"> <button class="btn">Save</button> </for
<form enctype="multipart/form-data" method="post" id='photo_details'>
<input type="text" name="f_name">
<input type="file" accept="image/*" name="profile_pic">
<button class="btn">Save</button>
</form>
假设我把f_的名字命名为“Carl”,把个人资料图片命名为“my_passport.png”,那么输出
f_名称:卡尔
profile_pic:[对象文件] 输出中的问题-
我得到了
f_name
的值,但是
我没有得到keyprofile\u pic的值,而是得到了[对象文件]
如何使用FormData对象获取文件名。
救命啊表单包含两个输入,一个输入类型为text
,另一个输入类型为file
,这意味着FormData
实例将有两个条目,一个具有字符串
值,另一个具有值
要获取文件名,您可以检查当前条目是否为文件
的实例的值,并访问其名称
属性。以下是一个例子:
for ([key, value] of form_data.entries()) {
let val;
if (value instanceof File) {
val = value.name;
} else {
val = value;
}
console.log(key + ': ' + val);
}
const fileInput = document.querySelector('input[type=file]');
const path = fileInput.value;
const fileName = path.split(/(\\|\/)/g).pop();
console.log('File name:', fileName);
您还可以直接从输入中获取文件名,例如:
for ([key, value] of form_data.entries()) {
let val;
if (value instanceof File) {
val = value.name;
} else {
val = value;
}
console.log(key + ': ' + val);
}
const fileInput = document.querySelector('input[type=file]');
const path = fileInput.value;
const fileName = path.split(/(\\|\/)/g).pop();
console.log('File name:', fileName);
仅当整个文档中只有一个file类型的输入时,第二个示例才有效。
<form enctype="multipart/form-data" method="post" id='photo_details'>
<input type="text" name="f_name">
<input type="file" accept="image/*" name="profile_pic">
<button class="btn" type="button" onclick="myFunction()">Save</button>
</form>
拯救
函数myFunction(){
让form_details=document.getElementById(“photo_details”);
让表单数据=新表单数据(表单详细信息);
form_data.entries()的([键,值]){
console.log(值);
}
}
已测试并运行。
<form enctype="multipart/form-data" onsubmit="return getData()" method="post" id='photo_details'>
<input type="text" name="f_name">
<input type="file" accept="image/*" name="profile_pic" id="file">
<input type="submit">
</form>
<script type="text/javascript">
function getData() {
let file_path = document.getElementById('file').value;
let file_name = file_path.split(/(\\|\/)/g).pop();
console.log(file_name);
return false;
}
</script>
函数getData(){
让file_path=document.getElementById('file').value;
让file\u name=file\u path.split(/(\\\\\\/)/g).pop();
console.log(文件名);
返回false;
}
这是否仅适用于控制台
?如果是这样,不要连接到字符串,而是使用多个参数:console.log(key,value)代码>。通过这种方式,您将记录实际的文件对象,并且您将能够对其进行导航以获取其名称
属性。。有些时候我真的会因为愚蠢的错误而忘记,我的错误,谢谢。。这个问题就在这里<代码>文件输入。值
不会返回文件name@Kaiido是的,它将包含整个路径。我将编辑我的答案。不,它将包含一个假的路径,这是不可用的,不应该使用。