简体   繁体   English

使用javascript在文件字段中未选择要上传的文件时弹出警报

[英]Alert popup when file is not selected for upload in file field using javascript

hi i am using php and mysql. 嗨,我正在使用php和mysql。

i have a form to add record for user. 我有一个为用户添加记录的表格。 user should prompt when he will not select any file to upload that you want to save data without image. 用户应在不选择任何要上传的文件时提示您要保存没有图像的数据。

Can we do that using javascript.. 我们可以使用javascript来做吗。

if any one know it would be appreciated.. 如果有人知道,将不胜感激。

Thanks in advance 提前致谢

You can verify the file input using javascript. 您可以使用javascript验证文件输入。

Here is an example: 这是一个例子:

function checkFile(yourForm){

    var fileVal = yourForm.elements['fileField'].value;

    //RegEx for valid file name and extensions.
    var pathExpression = "[?:[a-zA-Z0-9-_\.]+(?:.png|.jpeg|.gif)";


    if(fileVal != ""){
        if(!fileVal.toString().match(pathExpression) && confirm("The file is not a valid image. Do you want to continue?")){
            yourForm.submit();
        } else {
            return;
        }
    } else {
        if(confirm("Do you want to continue without adding image?")) {
            yourForm.submit();
        } else {
            return;
        }
    }
}

In your html 在你的HTML

<form name="yourForm" method="post" enctype="multipart/form-data"">
    <input type="file" name="fileField" />
    <input type="button" value="submit" onClick="checkFile(this.form)" />
</form>

Note pathExperssion can be customized. 注释pathExperssion可以自定义。 Another thing is checking the extension is not too reliable as anyone can inject a file name as extension. 另一件事是检查扩展名是否过于可靠,因为任何人都可以将文件名作为扩展名注入。 Click here for other info. 单击此处获取其他信息。

just check to see if the field is empty and then ask them if that's really what they want... 只需检查一下该字段是否为空,然后问他们这是否真的是他们想要的...

if( document.forms["uploadForm"].elements["imageField"].value == "" 
     && confirm("You have not added an image, are you sure you want to continue?")
 )
        upload();
    else
        doNothing();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM