上传文件大小前端验证还需要后端C#用时查

1. 前端JavaScript验证
你可以使用JavaScript在文件选择后进行大小验证。例如:

<form method="post" action="FileUpload.ashx" enctype="multipart/form-data">

  <input type="text" name="txtName" /><br />
  <input type="file" name="fileName" accept=".jpg,.jpeg,.png" /><br />
  <input type="submit" value="上传" />
</form>

<script>
document.getElementById('fileInput').addEventListener('change', function() {
    var file = this.files[0];
    if (file.size > 10485760) { // 10MB in bytes
        alert('File size exceeds the maximum allowed size of 10MB.');
        this.value = ''; // Clear the file input
        return false;
    }
});
</script>

 POST请求的一般处理程序FileUpload.ashx

using System;
using System.IO;
using System.Linq;
using System.Web;

namespace WebApp2019ASPX._01文件上传
{
    /// <summary>
    /// FileUpload 的摘要说明,上传要点:
    /// (1)端端html: form表单编码enctype=...formData 其它同表单元素
    /// (2)接收用Request.Files[0]类型HttpPostFile
    /// (3)
    /// </summary>
    public class FileUpload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string name = context.Request.Form["txtName"];
            HttpPostedFile upFile = context.Request.Files[0];//必须(1)Files得到HttpFileCollection集合,因为可以多选上传
            string fileNameFullPath = upFile.FileName;
            string fileName = Path.GetFileName(fileNameFullPath);
            string fileExt = Path.GetExtension(fileNameFullPath);
            string[] fileExts = { ".jpg", ".png" };
            if (upFile.ContentLength > 0)
            {
                if (fileExts.Contains(fileExt))
                {
                    string fileNameNew = "/ImageUpload/Upload_" + Guid.NewGuid().ToString() + fileExt;
                    upFile.SaveAs(context.Request.MapPath(fileNameNew));//必须(2) 仅此2行即可完成基础上传
                }
                else
                {
                    context.Response.Write("请选择图片文件");
                }
            }
            else
            {
                context.Response.Write("请选择要上传的图片");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted @ 2026-05-20 21:23  techNote  阅读(0)  评论(0)    收藏  举报