[英]How to check the file input to know if it's empty in node.js
I'm trying to check whether the user has actually chosen a file before pressing on upload or not, if so then check if the file is bigger than 4 MB. 我正在尝试检查用户是否确实选择了文件,然后再按上载,如果是,则检查文件是否大于4 MB。 If the user has pressed on upload without choosing a file then a message should be sent telling them to go back and choose a file.
如果用户在未选择文件的情况下按下上传按钮,则应发送一条消息,告诉他们返回并选择文件。 But this code doesn't seem to work.
但是这段代码似乎不起作用。
<div id="postUpload-wrapper"> <form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST"> <input type="text" id="postname" placeholder="Title" name="postname"> <br> <input id="fileupload" type="file" name="image"> <br> <input type="submit" id "uploadpost-btn" value="Upload" name="uploadpost"> </form> </div>
//UPLOAD A POST
router.post('/uploadpost', upload.single('image'), function(req, res){
var errors = "";
if(req.body.postname === ""){
errors += "Write a title";
res.send(errors);
return false;
}
//problem here
if(req.file.size === 0){
errors += "You need to choose a file";
res.send(errors);
return false;
}else{
if(req.file.size > 4000000){
errors += "Files can only be up to 4 MB in size";
res.send(errors);
return false;
}
}
I believe you should check this on the client side before allowing the file to be uploaded. 我相信您应在允许用户上传文件之前在客户端进行检查。
if(document.getElementById("uploadpost-btn").value != "") {
// you have a file
}
You can later check on the server-side. 您稍后可以在服务器端检查。 If
req.body
has any data then there was a file uploaded. 如果
req.body
有任何数据,那么有一个文件上传。
Try setting input type="submit"
element property disabled
to "true"
, use onchange
event of input type="file"
element to check if user selected file at FileList
object , set type="submit"
element to disabled="true"
, disabled="false"
if file.size
greater than 4000000
bytes . 尝试设置
input type="submit"
元素属性disabled
到"true"
,则使用onchange
的事件input type="file"
元件,以检查是否在用户选择的文件FileList
对象,设置type="submit"
元素来disabled="true"
,如果file.size
大于4000000
字节, file.size
disabled="false"
。 If file not selected , file size over 4000000
bytes submit button set to disabled 如果未选择文件,则文件大小超过
4000000
字节的“提交”按钮设置为“已禁用”
var input = document.getElementById("fileupload"); input.onchange = function() { var file = this.files, submit = this.nextElementSibling.nextElementSibling; if (file.length > 0) { if (file[0].size >= 4000000) { submit.disabled = true; alert("file size limit") } else { submit.disabled = false; console.log(this.files) } } }
<div id="postUpload-wrapper"> <form id="uploadpost-form" action="/uploadpost" enctype="multipart/form-data" method="POST"> <input type="text" id="postname" placeholder="Title" name="postname"> <br> <input id="fileupload" type="file" name="image"> <br> <input type="submit" id="uploadpost-btn" value="Upload" name="uploadpost" disabled="true"> </form> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.