首页 > 解决方案 > 在选择文件上附加默认图像

问题描述

我一直在寻找并努力寻找如何使用 JS/Jquery 在“选择文件”上附加默认图像的答案。我的目标是,如果用户忘记附加图像,我希望有一些默认的图像 url。因此,如果用户单击提交按钮,则会上传默认图像。我知道这样做的效率很低,我只想知道如何操作正在上传的文件。

<html>
    <body>
        <input type="file"/>
        <input type="submit">
    </body>
</html>

标签: javascriptjqueryfileinput

解决方案


您可以为提交按钮添加一个事件侦听器,并首先检查用户是否选择了任何文件

<input id="get-file" type="file">
<input id="submit-file" type="submit">
<script>

const inputField = document.querySelector('#get-file');
const submitButton  = document.querySelector('#submit-file');

submitButton.addEventListener('click', function() {
  // This is where you check whether user uploaded a file or not
  if (!inputField.value) {
    // Operate on the default file if user doesn't provide any

    // Make sure you exit the function
    return;
  }
  // User uploaded a file so operate on it here
});
</script>

推荐阅读