首页 > 解决方案 > 如何在文件名上传到asp.net之前检查文件名

问题描述

我打算做的是当我点击上传按钮时,系统会检查选择的文件名是否与我想要的文件名相同(在文件上传之前)。

string selectedValue = version.SelectedItem.Value;
string serverPath;

if (FileUpload1.PostedFile.FileName != "")
{
    if (selectedValue == "1")
    {
        // check extension of file before uploading
        if (FileUpload1.PostedFile.FileName == "MyApp.apk")
        {
            serverPath = "C:/MyPath/MyApp.apk";
            FileUpload1.PostedFile.SaveAs(serverPath);
            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('file has been uploaded successfully');window.location.href = '" + Request.RawUrl + "'; ", true);
        }
        else if (FileUpload1.PostedFile.FileName == "MyApp.ipa")
        {
            serverPath = "C:/MyPath/MyApp.ipa";
            FileUpload1.PostedFile.SaveAs(serverPath);
            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('file has been uploaded successfully');window.location.href = '" + Request.RawUrl + "'; ", true);
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Please select MyApp file to upload');window.location.href = '" + Request.RawUrl + "'; ", true);
        }
    }
}

但我得到的是,系统将首先上传文件并显示我设置的警报消息。

如何在默认上传栏出现之前先显示错误消息(选择了错误的文件)?

标签: c#asp.netfile-upload

解决方案


如果您需要在提交页面之前检查,您可以使用客户端 onchange 事件输入 type=file,如下所示:

    <html>
        <body>
            <form>
                <div>
                    file: <input type="file" id="fileupload" />
                </div>
            </form>
            <script>
                document.getElementById('fileupload').addEventListener('change', onUpload);
                function onUpload(e){
                    var files = this.files;
                    if ( files && files.length==1 
                        &&  ( files[0].name.toLowerCase() === "myapp.apk" || files[0].name.toLowerCase() === "myapp.ipa"  )
                        )
                    {
                        //allow to submit file
                    }
                    else{
                        //cancel form submission
                        this.value = "";
                        alert('Please select MyApp file to upload');
                    }
                }
            </script>
        </body>
    </html>

推荐阅读