javascript - 在选择文件上附加默认图像
问题描述
我一直在寻找并努力寻找如何使用 JS/Jquery 在“选择文件”上附加默认图像的答案。我的目标是,如果用户忘记附加图像,我希望有一些默认的图像 url。因此,如果用户单击提交按钮,则会上传默认图像。我知道这样做的效率很低,我只想知道如何操作正在上传的文件。
<html>
<body>
<input type="file"/>
<input type="submit">
</body>
</html>
解决方案
您可以为提交按钮添加一个事件侦听器,并首先检查用户是否选择了任何文件
<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>
推荐阅读
- react-native - 由于任务':react-native-image-picker:testDebugUnitTest'的执行失败,无法制作Azure持续集成构建管道
- apache-spark - 这个用例是否适合 Apache Spark?
- vba - 在 VBA 中抑制 PDF 转换错误消息
- c# - 由于 Microsoft.Toolkit.Uwp.UI.dll 上的错误,Uno 平台中的 WebAssembly 无法编译
- vue.js - 如何使用 Vue.js 跟踪谷歌分析活动
- javascript - React-Redux:如何从数组中添加每个项目
- powershell - 我们如何重新制作程序以运行并将新值保存在 c.csv 文件中?
- python - 乘法布尔矩阵
- typescript - 在打字稿项目中使用别名的问题
- python - 无法使用 DefaultAzureCredential 创建 DataFactoryManagementClient()?