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 == ""))
{
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提交文件的更多相关文章
- HttpClient Post Form提交文件/二进制数据
		
HttpClient httpClient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); Multipar ...
 - C# 模拟POST提交文件
		
http://blog.csdn.net/hellowjwang/article/details/19975635 public class HttpPost { /// <summary> ...
 - 【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.原因,工作队列被占用,只需 ...
 - 如何使用git命令添加文件和提交文件
		
1.进入指定文件夹内,启动 git bash here 2. 初始化文件夹 git init 3.开始添加文件 所有文件添加方法 git add . 单个文件添加方法 git add *.* 例如我的 ...
 - git gui 还原部分提交文件
		
有时候用git提交文件的时候会一起提交了多个文件,但是突然后悔了,想把其中一个文件撤销提交,其他文件不做修改.这个时候该怎么办呢? 我觉得有很多办法,比如可以先checkout到上次的提交,然后复制要 ...
 - js实现无刷新表单提交文件,将ajax请求转换为form请求方法
		
最近在做项目的时候遇到一个需要上传文件的需求,因为ajax请求是无法上传二进制文件流的,所以只能用form表单提交,而form提交有一个问题就是会使页面刷新,本文解决了form表单提交文件时页面刷新的 ...
 - TortoiseSVN提交文件的时候卡死
		
提交文件的时候卡死,查找很久,才发现原来是IP被修改了,郁闷
 - easyui  form提交文件(上传图片和文件)
		
<div id="dialogBtn"> <a class="easyui-linkbutton" href="#" on ...
 - Git学习之路(3)-提交文件到三个区
		
▓▓▓▓▓▓ 大致介绍 年过的差不多了,开始学习!小白学Git(持续更新) Git有三个工作区域: ◆ 工作区(Working Directory) ◆ 暂存区(Stage) ◆ 版本库(Reposi ...
 
随机推荐
- 修改Shp文件名称
			
IWorkspaceFactory factory = new ShapefileWorkspaceFactoryClass(); IWorkspace pworkspace = factory.Op ...
 - HDU1054 Strategic Game——匈牙利算法
			
Strategic Game Bob enjoys playing computer games, especially strategic games, but sometimes he canno ...
 - C语言 断言 总结
			
转载: http://wenda.so.com/q/1378817559065638?src=140 assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止 ...
 - 第七章 consul docker集群
			
--net=host:运行consul的docker镜像必须带有的参数,因为consul的consensus和gossip协议对于网络的延迟和丢包很敏感,所以引入额外的其他网络类型的层是不可取并且不必 ...
 - Android两个子线程之间通信
			
Android中,相信主线程和子线程之间的通信大家都不陌生了吧.在一次面试经历中被问到了两个子线程之间是如何进行通信的.哎呦!这可蒙住我了.后来回家研究了下,分享给大家. 其实android中线程通信 ...
 - 使用Cookie实现跨域单点登录的原理
			
对于构建分布式系统来说业务功能的物理部署会随着新业务模块的增加而增加或改变物理部署的位置.而每个用户都有统一的帐号作为我们登录系统时的一个认证.当新业务或子系统部署在不同的物理机上,我们去访问不同的业 ...
 - jQuery实现折叠下拉效果
			
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
 - 自定义View(三)实现简单的可拖动、可缩放的ImageView
			
实现技术主要用到1.多点触摸 2.matrix的矩阵,平移.缩放 根据手指的数量判断是进行的拖动.还是缩放动作 package com.bi.xintest; import android.cont ...
 - Trie / Radix Tree / Suffix Tree
			
Trie (字典树) "A", "to", "tea", "ted", "ten", "i ...
 - 提高SQL查询效率(SQL优化)
			
要提高SQL查询效率where语句条件的先后次序应如何写 http://blog.csdn.net/sforiz/article/details/5345359 我们要做到不但会写SQL,还要做到 ...