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:\temp";              

                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("\r\n" + 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值