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 ...
随机推荐
- Host 'XXX' is not allowed to connect to this MySQL server 解决方案/如何开启MySQL的远程帐号
www.cnblogs.com/zhangzhu/archive/2013/08/22/3274831.html 如何开启MySQL的远程帐号-1)首先以 root 帐户登陆 MySQL 在 Wind ...
- autoLayout约束图解
- hdu 1106 排序(水题)
题目描述: 输入一行数字,如果我们把这行数字中的'5'都看成空格,那么就得到一行用空格分割的若干非负整数(可能有些整数以'0'开头,这些头部的'0'应该被忽略掉,除非这个整数就是由若干个'0'组成的, ...
- textarea之placeholder
placeholder 属性适用于以下的 <input> 类型:text, search, url, telephone, email 以及 password.这个属性是html5才有的新 ...
- c#.net全站防止SQL注入类的代码
using System;using System.Collections.Generic;using System.Linq;using System.Web; /// <summary> ...
- MySql密码忘记解决方法
1.先杀掉mysqld-nt.exe 进程,有很多种方法,最简单是在CMD里输入net stop mysql 2.CMD路径切换到MySQL的安装目录下的bin里 输入mysqld-nt.exe - ...
- DataRead 和DataSet区别
dataset表示一个数据集,是数据在内存中的缓存. 可以包括多个表DatSet 连接数据库时是非面向连接的.把表全部读到Sql中的缓冲池,并断开于数据库的连接 datareader 连接数据库时是面 ...
- svg path中的贝塞尔曲线
首先介绍以下什么是贝塞尔曲线 贝塞尔曲线又叫贝茨曲线(Bezier),由两个端点以及若干个控制点组成,只有两个端点在曲线上,控制点不在曲线上,只是控制曲线的走向. 控制点个数为0时,它是一条直线; 控 ...
- JavaWeb 学习006-4个页面,5条sql语句(添加、查看、修改、删除)
今天遇到的问题: 1. 在list页面上添加信息时候,跳转到doAdd页面后,点击保存按钮,能够跳转回list页面,但是新增的信息不能显示出来,就像是没有执行添加操作一样. 这是什么问题? ①是不是到 ...
- WebStorm 8.0.1 注册码
username:24718-12042010 key:00001h6wzKLpfo3gmjJ8xoTPw5mQvY YA8vwka9tH!vibaUKS4FIDIkUfy!!f 3C"rQ ...