先建立一个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 == ""))
{
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, , postFile.ContentLength); string savePath = Path.Combine(saveDirectory, postFileName);
using (FileStream stream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
{
stream.Write(bufferFile, , 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 = ;
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, , 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, , bufferFileInfo.Length);
} return bufferFileInfo; } private void btnSubmit_Click(object sender, EventArgs e)
{
Submit("http://localhost.:3558/Server.ashx", "abc", "", "F:\\报表下载清单2.xls");
}
}
}

C#实现HttpPost提交文件的更多相关文章

  1. HttpClient Post Form提交文件/二进制数据

    HttpClient httpClient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); Multipar ...

  2. C# 模拟POST提交文件

    http://blog.csdn.net/hellowjwang/article/details/19975635 public class HttpPost { /// <summary> ...

  3. 【svn】在提交文件是报错:previous operation has not finished;run 'cleanup' if it was interrupted

    1.svn在提交文件是报错:previous operation has not finished;run 'cleanup' if it was interrupted2.原因,工作队列被占用,只需 ...

  4. 如何使用git命令添加文件和提交文件

    1.进入指定文件夹内,启动 git bash here 2. 初始化文件夹 git init 3.开始添加文件 所有文件添加方法 git add . 单个文件添加方法 git add *.* 例如我的 ...

  5. git gui 还原部分提交文件

    有时候用git提交文件的时候会一起提交了多个文件,但是突然后悔了,想把其中一个文件撤销提交,其他文件不做修改.这个时候该怎么办呢? 我觉得有很多办法,比如可以先checkout到上次的提交,然后复制要 ...

  6. js实现无刷新表单提交文件,将ajax请求转换为form请求方法

    最近在做项目的时候遇到一个需要上传文件的需求,因为ajax请求是无法上传二进制文件流的,所以只能用form表单提交,而form提交有一个问题就是会使页面刷新,本文解决了form表单提交文件时页面刷新的 ...

  7. TortoiseSVN提交文件的时候卡死

    提交文件的时候卡死,查找很久,才发现原来是IP被修改了,郁闷

  8. easyui form提交文件(上传图片和文件)

    <div id="dialogBtn"> <a class="easyui-linkbutton" href="#" on ...

  9. Git学习之路(3)-提交文件到三个区

    ▓▓▓▓▓▓ 大致介绍 年过的差不多了,开始学习!小白学Git(持续更新) Git有三个工作区域: ◆ 工作区(Working Directory) ◆ 暂存区(Stage) ◆ 版本库(Reposi ...

随机推荐

  1. hdu4044 GeoDefense

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4044 题意:一个树上的塔防游戏.给你n个结点的树,你要在树结点上建塔防御,在第 i 个结点上有 ki ...

  2. 点击更多button显示更多数据的功能实现思路代码

    此功能是根据自己思路去慢慢做出来的,做的不够专业,希望有懂这个的前辈给自己指点指点. //分界线———————————————————————————————————————————————————— ...

  3. SWT布局管理器

    一.充满式布局管理器(FillLayout类) FillLayout类是最简单的布局类,它把组件摆放成一行或者一列,并强制组件大小一致.一般,组件的高度与最高的组件一致,宽度与最宽的组件相同.,它里面 ...

  4. python第十九天-----Django进阶

    1.机智的小django为我你们提供了快捷的表单验证! from django.shortcuts import render, HttpResponse,redirect from django i ...

  5. UITableView 使用

    关键字 •UITableView •UITableViewDataSource •UITableViewDelegate •UITableViewCell •MVC   运行结果

  6. DataRead 和DataSet区别

    dataset表示一个数据集,是数据在内存中的缓存. 可以包括多个表DatSet 连接数据库时是非面向连接的.把表全部读到Sql中的缓冲池,并断开于数据库的连接 datareader 连接数据库时是面 ...

  7. iOS 10 开发 相机相关的适配

    升级 iOS 10 之后目测坑还是挺多的,记录一下吧,看看到时候会不会成为一个系列. 直入正题吧 今天在写 Swift 3 相关的一个项目小小练下手,发现调用相机,崩了.试试看调用相册,又特么崩了.然 ...

  8. 常见sizeof 笔试题

    最近面试过程中遇到了很多很多sizeof的问题. 现在总结一下: #include <stdio.h> #include <string.h> void fun(int arr ...

  9. Jackson fasterxml跟codehaus的区别 (fasterxml vs. codehaus) -- 转载

    Jackson fasterxml和codehaus的区别: 他们是Jackson的两大分支.也是两个版本的不同包名.Jackson从2.0开始改用新的包名fasterxml:1.x版本的包名是cod ...

  10. C#数据结构选择

    选择一个合适的数据结构会对程序的性能有着显著的提高 线性表和链表: 1.LinkedList<T>:适合于元素数组不固定,存在大量列表的头尾添加动作场合.其它可使用List<T> ...