微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用最基础的 ASP.NET ASHX 实现一个文件上传功能

 

简单的一个 ASHX:

<%@ WebHandler Language="C#" Class="TestHandler" %>

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

public class TestHandler : IHttpHandler  
{
    public void ProcessRequest(HttpContext context)  
    {
        context.Response.ContentType = "text/html;charset=utf-8";
        
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file = context.Request.Files[0];
            string fileName = Path.GetFileName(file.FileName);
            string path = context.Server.MapPath("/" + fileName);
            file.SaveAs(path);
            context.Response.Write(@"success: " + path);
        }
        
        context.Response.Write(@"
        <form action='test.ashx' method='post' enctype='multipart/form-data'>
            <input type='file' name='upload_file' />
            <input type='submit'>
        </form>");
    }
    
    public bool IsReusable { get { return false; } }
}

上传遇到大小限制时,可以修改一下 web.config 文件

<configuration>
    <system.web>
        <customErrors mode="Off"/>
        <!-- 最大请求长度,单位为KB(千字节),认为4M,设置为1G,上限为2G -->
        <httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
    </system.web>
    <system.webServer> 
        <!-- 允许上传文件长度,单位字节(B),认为30M,设置为1G,最大为2G -->
        <security>
            <requestfiltering>
                <requestLimits maxAllowedContentLength="1073741824"/>
            </requestfiltering>
        </security>
    </system.webServer>
</configuration>

参考:

https://www.cnblogs.com/g1mist/p/3222255.html

https://blog.csdn.net/HerryDong/article/details/100549765

https://www.cnblogs.com/xielong/p/10845675.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐