c# - 如何在文件名上传到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);
}
}
}
但我得到的是,系统将首先上传文件并显示我设置的警报消息。
如何在默认上传栏出现之前先显示错误消息(选择了错误的文件)?
解决方案
如果您需要在提交页面之前检查,您可以使用客户端 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>
推荐阅读
- sql - 如何推断从一种状态转换到另一种状态的指标?
- python-3.x - 如何检查 MongoDB 集合中的字典中是否存在键、值对
- python - Python 图形
- c# - AsyncFunction().GetAwaiter().GetResult() 和 Task.Run(() => AsyncFunction).GetAwaiter().GetResult() 有什么区别?
- mariadb - MariaDB CONCAT / GROUP_CONCAT
- python - gzip API 响应问题(python)
- python - 使用字典理解过滤 django 模型
- python - 将 2d Numy 数组添加到 1d Numpy 数组
- microsoft-graph-api - 特定日历的奇怪确定性“服务不可用”错误
- java - 将日期发送到 postgresql