簡體   English   中英

如何檢查文件輸入以了解node.js中是否為空

[英]How to check the file input to know if it's empty in node.js

我正在嘗試檢查用戶是否確實選擇了文件,然后再按上載,如果是,則檢查文件是否大於4 MB。 如果用戶在未選擇文件的情況下按下上傳按鈕,則應發送一條消息,告訴他們返回並選擇文件。 但是這段代碼似乎不起作用。

 <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;
    }
}

我相信您應在允許用戶上傳文件之前在客戶端進行檢查。

if(document.getElementById("uploadpost-btn").value != "") {
   // you have a file
}

您稍后可以在服務器端檢查。 如果req.body有任何數據,那么有一個文件上傳。

嘗試設置input type="submit"元素屬性disabled"true" ,則使用onchange的事件input type="file"元件,以檢查是否在用戶選擇的文件FileList對象,設置type="submit"元素來disabled="true" ,如果file.size大於4000000字節, file.size disabled="false" 如果未選擇文件,則文件大小超過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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM