先建立一个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. Unity Application 前后台切换调用关系

    [Unity Application 前后台切换调用关系] http://blog.csdn.net/aa4790139/article/details/48087877

  2. web测试安全性常见问题

    web测试安全性常见问题                  一.             登录账号明文传输 1.  问题一:登录账号密码或者修改密码明文传输 现象:目前物流对内的java系统基本上都是 ...

  3. oracle 调用java

    1.首先在PL/SQL中创建JAVA类,并编译 例如:这个是到的一个查询目录下面文件列表的java类 创建此java 类用: create or replace and compile java so ...

  4. 安装Linux系统Fedora 23

    搭建了一个Linux(Fedora 23)环境,用于学习.实验. [TOC] 1 安装Fedora 以前一直只会光盘安装,刻录了好多个版本的distros,用完即弃在一旁.很浪费. 此次学会了在Lin ...

  5. LDAP与Samba

    默认的Samba服务器支持本地系统用户(smbpasswd添加后)访问Samba资源,不支持OpenLDAP服务器账号访问Samba共享资源 目的:配置完后,OpenLDAP每新增一个用户,就自动支持 ...

  6. 二、innerHTML应用测试

    <!DOCTYPE html><html><head><meta charset="UTF-8"><title>inne ...

  7. SOCKS 5协议详解(转)

    笔者在实际学习中,由于在有些软件用到了socks5(如oicq,icq等),对其原理不甚了解,相信很多朋友对其也不是很了解,于是仔细研读了一下rfc1928,觉得有必要译出来供大家参考. 1.介绍: ...

  8. dojo grid 编辑问题

    今天dojo grid编辑小问题,找了半天才找到问题, 1.问题 2.原因 数据单元没有索引列->id 3.修改前代码 <!DOCTYPE HTML> <html lang=& ...

  9. NSMutableAttributedString的使用

    1.设置字符串中数字字符串的颜色: // 设置字符串中数字的颜色 - (void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange: ...

  10. ww

    #!bin/python #coding=utf-8 """ Create by he """ import sys import re i ...