使用 javascript 或 jquery 以 html 形式上传默认图像 [英] Uploading a default image in html form using javascript or jquery
本文介绍了使用 javascript 或 jquery 以 html 形式上传默认图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一个具有不同输入字段的 html 表单,其中一个是 [type = file] 并且用户必须向其上传图像,如果用户没有上传图像并点击提交,我喜欢使用我自己的默认图像更新它,然后提交表单.
Consider a html form which has different input fields in which one of them is of [type = file] and the user has to upload an image to it, and if the user does not upload an image and clicks submit, I like to update it with a default image of my own and then submit the form.
有人知道如何实现吗?
提前致谢...
我当前的代码是这样的
if(document.getElementById("image") === "") {
document.image.value="image.jpg";
}
form {
display: block;
position: relative;
}
input {
position:relative;
margin-bottom:5px;
}
<form id="myform">
<input type="text" id="name" placeholder="Enter your name" required><br>
<input type="email" placeholder="Enter your email" id="mail" required><br>
<input type="file" accept=".jpg,.png" id="image"><br>
<button type="submit">Submit</button>
</form>
推荐答案
//HTML
<form id="myform">
<input type="text" name="username" id="name" placeholder="Enter your name" required><br>
<input type="email" name="email" placeholder="Enter your email" id="mail" required><br>
<input type="file" name="image" accept=".jpg,.png" id="image"><br>
<button type="submit">Submit</button>
</form>
//Javascript
// Javascript
let defaultFileImage = null;
let url = 'image.jpg';
// convert url image to File object
fetch(url)
.then(res => res.blob())
.then(blob => {
defaultFileImage = new File([blob], 'image.jpg', blob)
});
// submit form
document.getElementById('myform').addEventListener('submit', (e) => {
e.preventDefault();
var myform = document.forms.myform;
var formData = new FormData(myform);
var userImage = formData.get('image');
if(userImage.name) {
console.log(userImage)
}
else {
console.log(defaultFileImage)
}
});
这篇关于使用 javascript 或 jquery 以 html 形式上传默认图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文