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"> ...
随机推荐
- Ubuntu16.04下的modules模块编译加载
一.首先编写对应的驱动程序的相关内容:(最简单的hello.c程序) #include<linux/init.h> #include<linux/module.h> MODUL ...
- GYM 101755 K.Video Reviews 【贪心】+【二分】
<题目链接> 题目大意: 一家公司想让n个人给他们的产品评论,所以依次去找这n个人,第i个人会评论当且仅当已经有ai个人评论或他确实对这个产品感兴趣,但是这n个人都不对这个产品感兴趣,问这 ...
- springboot2 config_toolkit 并且设置全局获取数据GlobalUtil
本文只贴相关代码段,完整代码请移步至本人github,若是喜欢,可以star给予支持 作者:cnJun 博客专栏: https://www.cnblogs.com/cnJun/ 本文实现目标 重要的配 ...
- flume初识
一.flume特点 flume是目前大数据领域数据采集的一个利器,当然除了flume还有Fluentd和logstash,其他的目前来说并没有深入的了解,但是我觉得flume能够在大数据繁荣的今天屹立 ...
- flex 布局的复习
- vue中的表单
v-model指令实现表单双向绑定数据.触发文本框的input事件.一.文本框 <div id="J_app"> <p>{{ info }}</p&g ...
- jmeter使用Beanshell预处理器从指定列表中获取随机值
变量mynation从列表{"china", "US", "UK"}中随机取值 String[] nation = new String[] ...
- GIL锁、进程池与线程池
1.什么是GIL? 官方解释: ''' In CPython, the global interpreter lock, or GIL, is a mutex that prevents multip ...
- 虚拟主机的IIS连接数和访问流量限制各是什么
网址:http://zhidao.baidu.com/question/40279863IIS连接数,就是你的网站同时允许多少个人连接你的网站.IIS连接数为100就是,同时允许100人连接你的网站, ...
- Visual Assist X 助手下载
链接:http://pan.baidu.com/s/1pLUErhT 密码:c6in