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

因为各种限制,不能直接向被远程操作的服务器(Windows)传输文件,但端口没有做限制,剪贴板也可以操作的

本来是想用 IIS 自带的 FTP,但是折腾半天也没成功

故想到用 IIS 搭建一个最简单的 ASP.NET 网站,建立一个 ASHX 来作为页面和接收上传文件

1、那么就建立一个简单的 ASHX,保存为文件如:test.ashx,将 IIS 站点指向该文件所在目录,在远程电脑上访问即可。

<%@ 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; } }
}

2、当上传大文件时,可能会遇到大小限制时,可以再建立或修改 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


输了你,赢了世界又如何...
原文地址:https://www.cnblogs.com/xwgli/p/15664832.html