C#使用HttpWebRequest和HttpWebResponse上传文件示例
C#使用HttpWebRequest和HttpWebResponse上传文件示例
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
namespace ConsoleApplication1
{
public static class HttpHelper
{
private static readonly Encoding DEFAULTENCODE = Encoding.UTF8;
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data)
{
return HttpUploadFile(url, file, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="file"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string file, NameValueCollection data, Encoding encoding)
{
return HttpUploadFile(url, new string[] { file }, data, encoding);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data)
{
return HttpUploadFile(url, files, data, DEFAULTENCODE);
}
/// <summary>
/// HttpUploadFile
/// </summary>
/// <param name="url"></param>
/// <param name="files"></param>
/// <param name="data"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
//1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;
using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (data != null)
{
foreach (string key in data.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, data[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
}
//1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[4096];
int bytesRead = 0;
for (int i = 0; i < files.Length; i++)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
}
//1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
}
}
}
2.调用示例:
using System.Collections.Specialized;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
NameValueCollection data = new NameValueCollection();
data.Add("name", "木子屋");
data.Add("url", "http://www.mzwu.com/");
Console.WriteLine(HttpHelper.HttpUploadFile("http://localhost/Test", new string[] { @"E:\Index.htm", @"E:\test.rar" }, data));
Console.ReadKey();
}
}
}
参考资料
[1].ASP无组件上传原理:http://www.jjshang.com/jjshangnew/book/asp/mustfiles/jjupload.pdf
[2].Upload files with HTTPWebrequest (multipart/form-data):http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
C#使用HttpWebRequest和HttpWebResponse上传文件示例的更多相关文章
- PHP上传文件示例
虽然大多数人认为Web只包含网页,但HTTP协议实际上可以传输任何文件,如office文档.PDF.可执行文件.AVI.压缩文件及各种其他文件类型.虽然FTP在历史上一直是向服务器上传文件的标准方式, ...
- python网络编程--FTP上传文件示例
1.基础版(供学习了解原理使用,low) server服务端 import socket import struct import json server = socket.socket() ip_p ...
- Python--day67--CBV和FBV、Request对象及上传文件示例
1,CBV版添加新的出版社 views.py文件 urls.py文件 2,Request对象: request对象 当一个页面被请求时,Django就会创建一个包含本次请求原信息的HttpReques ...
- php 上传文件 示例
<?php header("content-type:text/html;charset=utf-8"); error_reporting(E_ALL); //session ...
- MVC上传文件示例
[HttpPost] public void SaveFile(FormCollection form) { var c = Request.Files.Count; ]; } @using (Htm ...
- 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件
[源码下载] 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...
- PHP上传文件详解 错误提示
首先在php.ini里配置上载文件.有以下几个重要的配置单: 选项 默认值 说明 post_max_size 8M 控制以后的POST请求的最大规模.必须大于upload_max_filesize选项 ...
- MVC3+jquery Uploadify 上传文件
最近做项目用到了上传图片的功能,以前也写过这类代码,不过都是用传统的file标签,今天整理一个好用的插件Uploadify..都做了一些注释,一看便知. 可以去官网下载最新的:Uploadify下载地 ...
- HttpWebRequest上传文件(Excel等)
//上传代码/// <summary> /// 文件上传 /// </summary> /// <param name="strAddress"> ...
随机推荐
- 爬虫3 requests基础之 乱码编码问题
import requests res = requests.get('http://www.quanshuwang.com') res.encoding = 'gbk' print(res.text ...
- HDU 2389 Rain on your Parade 最大匹配(模板题)【HK算法】
<题目链接> 题目大意:有m个宾客,n把雨伞,预计时间t后将会下大雨,告诉你每个宾客的位置和速度,每把雨伞的位置,问你最多几个宾客能够拿到伞. 解题分析: 本题就是要我们求人与伞之间的最大 ...
- asp.net core选项Options模块的笔记
这篇博客是写给自己看的.已经不止一次看到AddOptions的出现,不管是在.net core源码还是别人的框架里面,都充斥着AddOptions.于是自己大概研究了下,没有深入,因为,我的功力还是不 ...
- Meet Hadoop
全书目前刚看到3.2,博客进度会慢一些,很多问题和例子需要操作一遍才能弄清楚. Why Hadoop 解决的问题 Hadoop的优势 小黄象Hadoop? 学习路线 简单总结 Why Hadoop 解 ...
- BZOJ.4771.七彩树(可持久化线段树)
BZOJ 考虑没有深度限制,对整棵子树询问怎么做. 对于同种颜色中DFS序相邻的两个点\(u,v\),在\(dfn[u],dfn[v]\)处分别\(+1\),\(dfn[LCA(u,v)]\)处\(- ...
- php 将两个数组进行相加 http://blog.csdn.net/lcstrive/article/details/38331487
刚刚在网上看到一个提问. 数组Array ( [0] => 1 [1] => 2 )和数组Array ( [0] => 5 [1] => 6 ) 怎么让他们想加得出: 数组Ar ...
- Python3从零开始爬取今日头条的新闻【三、滚动到底自动加载】
Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...
- [POJ2287][Tyvj1048]田忌赛马 (贪心+DP)
瞎扯 很经典的一道题 考前才打 我太菜了QAQ 就是先贪心排序了好 然后在DP 这样比直接DP更容易理解 (其实这题做法还有很多) 代码 #include<cstdio> #include ...
- C++学习笔记55:流类库与输入输出
I/O流的概念及流类库的结构 程序与外界环境的信息交换 当程序与外界环境进行信息交换时,存在着两个对象:程序中的对象,文件对象. 流是一种抽象,负责在数据的生产者和数据的消费者之间建立联系,并管理数据 ...
- AtCoder Regular Contest 080 [CDEF]
C - 4-adjacent Time limit : 2sec / Memory limit : 256MB Problem Statement We have a sequence of leng ...