HttpWebRequest上传文件(Excel等)
//上传代码
/// <summary>
/// 文件上传
/// </summary>
/// <param name="strAddress">路径地址,不包括服务地址</param>
/// <param name="postedFile"></param>
/// <returns></returns>
public static IResponseResult HttpPostFile(string strAddress, HttpPostedFile postedFile,string reFileName)
{
string url = ConfigHelper.GetConfigString("PAOfferSystemAddress") + strAddress;
//1>创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//2>Cookie容器(保存cookie,只是上传文件,则可以注释掉)
//request.CookieContainer = cookieContainer;
request.Method = "POST";
request.Timeout = ;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.KeepAlive = true; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");//分界线
byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary;//内容类型 //3>表单数据模板
//string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
//4>读取流
byte[] buffer = new byte[postedFile.ContentLength];
postedFile.InputStream.Read(buffer, , buffer.Length); //5>写入请求流数据
string strHeader = "Content-Disposition:application/x-www-form-urlencoded; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
strHeader = string.Format(strHeader,
"filedata",
//postedFile.FileName,
reFileName + postedFile.FileName,
postedFile.ContentType);
//6>HTTP请求头
byte[] byteHeader = System.Text.ASCIIEncoding.UTF8.GetBytes(strHeader);
StringBuilder sbBody=new StringBuilder ();
sbBody.Append(System.Text.Encoding.UTF8.GetString(boundaryBytes));
sbBody.Append(System.Text.Encoding.UTF8.GetString(byteHeader));
sbBody.Append(System.Text.Encoding.UTF8.GetString(buffer));
sbBody.Append(System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n")));
string headValue = Encrpt(sbBody.ToString());//加密
request.Headers.Add("OfferServiceAuthorization", headValue);
request.Headers.Add("CustomID", ConfigurationManager.AppSettings["CustomID"]); try
{
using (Stream stream = request.GetRequestStream())
{
#region 写入请求流(表单数据)
//写入请求流(表单数据)
//if (null != parameters)
//{
// foreach (KeyValuePair<string, object> item in parameters)
// {
// stream.Write(boundaryBytes, 0, boundaryBytes.Length);//写入分界线
// byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formdataTemplate, item.Key, item.Value));
// stream.Write(formBytes, 0, formBytes.Length);
// }
//}
#endregion
//6.0>分界线============================================注意:缺少次步骤,可能导致远程服务器无法获取Request.Files集合
stream.Write(boundaryBytes, , boundaryBytes.Length);
//6.1>请求头
stream.Write(byteHeader, , byteHeader.Length);
//6.2>把文件流写入请求流
stream.Write(buffer, , buffer.Length);
//6.3>写入分隔流
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, , trailer.Length);
//6.4>关闭流
stream.Close();
}
string responseContent = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
responseContent = streamReader.ReadToEnd();
response.Close();
request.Abort();
} return JsonConvertHelper.DataContractToModel<IResponseResult>(responseContent);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} //服务器代码
HttpPostedFile file = Context.Request.Files["filedata"];//获取上传文件
if (null == file || file.ContentLength == )
{
IResponseResult responseResult = new IResponseResult();
responseResult.Status = ResponseStatus.Fail;
responseResult.Message = "Upload file is invalid";
//to json返回结果
string toJson = JsonConvertHelper.ToJson(responseResult);
Response.Write(toJson);
}
else
{
string filePath = Server.MapPath("~/File/Excel");
if (!Directory.Exists(filePath))//判断文件夹是否存在
{
Directory.CreateDirectory(filePath);//不存在则创建文件夹
}
file.SaveAs(string.Format("{0}/{1}", filePath, file.FileName));
IResponseResult responseResult = new IResponseResult();
responseResult.Status = ResponseStatus.Success;
string toJson = JsonConvertHelper.ToJson(responseResult);
Response.Write(toJson);
}
HttpWebRequest上传文件(Excel等)的更多相关文章
- 关于HttpWebRequest上传文件
我们web 操作离不开 http请求响应 HttpWebRequest上传文件也是一样的道理 下面码一些代码: private void UploadFile(string strRequestUri ...
- HTTPWebrequest上传文件--Upload files with HTTPWebrequest (multipart/form-data)
使用HTTPWebrequest上传文件遇到问题,可以参考Upload files with HTTPWebrequest (multipart/form-data)来解决 https://stack ...
- C#在WinForm下使用HttpWebRequest上传文件
转自:http://blog.csdn.net/shihuan10430049/article/details/3734398 这段时间因项目需要,要实现WinForm下的文件上传,个人觉得采用FTP ...
- [转]C#在WinForm下使用HttpWebRequest上传文件并显示进度
/// <summary> /// 将本地文件上传到指定的服务器(HttpWebRequest方法) /// </summary> /// <param name=&qu ...
- 上传读取Excel文件数据
/// <summary> /// 上传读取Excel文件数据 /// 来自http://www.cnblogs.com/cielwater /// </summary> // ...
- C# 使用HttpWebRequest通过PHP接口 上传文件
1:上传文件实例 public void UploadXMLLog(string xmlpath) { NameValueCollection nvc = ne ...
- .NET 客户端上传本地excel文件到服务器上,并在客户端显示
// 上传按钮 protected void btnUp_Click(object sender, EventArgs e) { bool b = Upload(fuExcel); // 上传exce ...
- springMVC从上传的Excel文件中读取数据
示例:导入客户文件(Excle文件) 一.编辑customer.xlsx 二.在spring的xml文件设置上传文件大小 <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1 ...
- ASP.NET上传文件到远程服务器(HttpWebRequest)
/// <summary> /// 文件上传至远程服务器 /// </summary> /// <param name="url">远程服务地址 ...
随机推荐
- (三)原生JS实现 - 插件 - 弹出层
创建遮罩层 _createCover: function() { var newMask = document.createElement("div"); newMask.id = ...
- MfC基础--绘图基础--win32
1.vc使用的控件分为三类: windows标准控件--MFC对这些进行了再封装 ActiveX 控件 其他MFC控件类 2.CWind是所有窗口的基类 3.GDI也属于一种API,主要用于绘图,(G ...
- shell中的case表达式
语法格式 case var in pattern1 | patter2) command1 command2;; pattern3) command1 command2;; *) default co ...
- AIX下解决POWERHA的脑裂问题
一.安装创建并发vg时必需的软件包clvm包,该包安装.升级.后必须重启os clvm包的描述:Enhanced Concurrent Logical Volume Manager 软件包在aix61 ...
- talos项目记录
1. 跑schedule : php src/cli-schedule/cli.php -a sales.coupon.offer-coupons 所用方法在schedule里
- 帝国cms实现自动生成缩略图和自动分页功能
无论你手工发布,还是采集而来,免不了要进行手工操作弄缩略图,不然标题图片没有,挺烦人的 只需一次设定,就可以在文章编辑框里自动勾选上分页和生成缩略图,免除你次次进行操作的麻烦,好了,废话不多说,上菜“ ...
- Modified Kaprekar Numbers
Link: https://www.hackerrank.com/challenges/kaprekar-numbers from __future__ import print_function d ...
- tableView点击后取消选中效果
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES]; @impo ...
- The Contiki build system 编译系统
The Contiki build system======================== The Contiki build system is designed to make it eas ...
- ImageMaigck不支持中文路径的问题
不知道咋回事. 回顾下: char* pTest1 = "测试.txt"; wchar_t* pTest2 = L"测试.txt"; 以上是pTest1指向的内 ...