C#实现HttpPost提交文件

先建立一个WebApplication

Web.config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  
    <system.web>

      <!--<globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312"/>-->
      <compilation debug="true" />

      <authentication mode="Windows" />

    </system.web>
</configuration>

Server.ashx

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.IO;
using System.Text;

namespace WebApplication1
{
  
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Server : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string saveDirectory = @"f:	emp";              

                string user = context.Request.Form["user"].ToString();
                string pass = context.Request.Form["pass"].ToString();

                if (!(user == "abc" && pass == "123"))
                {
                    context.Response.Write("验证出错!");
                }
                
                HttpPostedFile postFile = context.Request.Files["myFile"];
                string postFileName = Path.GetFileName(postFile.FileName);
                byte[] bufferFile = new byte[postFile.ContentLength];
                postFile.InputStream.Read(bufferFile, 0, postFile.ContentLength);

                string savePath = Path.Combine(saveDirectory, postFileName);
                using (FileStream stream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                {
                    stream.Write(bufferFile, 0, bufferFile.Length);
                    stream.Flush();
                    stream.Close();
                }

                context.Response.Write("提交成功!");
            }
            catch (Exception ex)
            {              
                context.Response.Write(ex.Message);
            }
        }

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

选建个html测试下

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>测试提交</title>
</head>
<body>

     <form action="Server.ashx" enctype="multipart/form-data" method="post">
      <input type="text" name="user" value="abc" />
      <input type="text" name="pass" value="123"/>
      <input type="file" name="myFile" />
      <input type="submit" />
   
     </form>

</body>
</html>

再用C#按Http协议提交:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace WinFormHttpPost
{
    public partial class Form1 : Form
    {
        private Encoding currentEncode = Encoding.GetEncoding("utf-8");

        public Form1()
        {
            InitializeComponent();
        }

        private void Submit(string url, string user, string pass, string filePath)
        {
            string boundary = Guid.NewGuid().ToString();
            string beginBoundary = "--" + boundary;
            string endBoundary = "--" + boundary + "--";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;

            StringBuilder sbBody = new StringBuilder();
            sbBody.AppendLine(beginBoundary);
            sbBody.AppendLine("Content-Disposition: form-data; name="user"");
            sbBody.AppendLine();
            sbBody.AppendLine(user);

            sbBody.AppendLine(beginBoundary);
            sbBody.AppendLine("Content-Disposition: form-data; name="pass"");
            sbBody.AppendLine();
            sbBody.AppendLine(pass);

            sbBody.AppendLine(beginBoundary);
            sbBody.AppendLine(string.Format("Content-Disposition: form-data; name="myFile"; filename="{0}"", filePath));
            sbBody.AppendLine("Content-Type: application/octet-stream");
            sbBody.AppendLine();

            byte[] bufferContent = currentEncode.GetBytes(sbBody.ToString());
            byte[] bufferFile = GetFileByte(filePath);
            byte[] bufferEndBoundary = currentEncode.GetBytes("
" + endBoundary);

            byte[] bufferBody = new byte[bufferContent.Length + bufferFile.Length + bufferEndBoundary.Length];
            int startIndex = 0;
            bufferContent.CopyTo(bufferBody, startIndex);
            startIndex += bufferContent.Length;
            bufferFile.CopyTo(bufferBody, startIndex);
            startIndex += bufferFile.Length;
            bufferEndBoundary.CopyTo(bufferBody, startIndex);

            request.ContentLength = bufferBody.Length;
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(bufferBody, 0, bufferBody.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, currentEncode);

            tbResult.Text = readStream.ReadToEnd();
            response.Close();
            readStream.Close();
        }

        private byte[] GetFileByte(string filePath)
        {
            byte[] bufferFileInfo = null;
            using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                bufferFileInfo = new byte[stream.Length];
                stream.Read(bufferFileInfo, 0, bufferFileInfo.Length);
            }

            return bufferFileInfo;

        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            Submit("http://localhost.:3558/Server.ashx", "abc", "123", "F:\报表下载清单2.xls");
        }
    }
}
原文地址:https://www.cnblogs.com/siso/p/3692530.html