码迷,mamicode.com
首页 > Windows程序 > 详细

C# 模拟Form表单上传文件方法

时间:2015-08-07 10:53:48      阅读:414      评论:0      收藏:0      [点我收藏+]

标签:

public static string UploadFile(string url, HttpPostedFileBase file,string FieldName)
{
Stream fs = file.InputStream;
if (!fs.CanRead)
{
return "";
}
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();

string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string PREFIX = "--", LINE_END = "\r\n";

StringBuilder sb = new StringBuilder();
sb.Append(PREFIX + boundary + LINE_END);
sb.Append("Content-Disposition: form-data; name=\"" + FieldName + "\"; filename=\"" + file.FileName + "\"" + LINE_END);
sb.Append("Content-Type: " + file.ContentType + LINE_END + LINE_END);
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary=" + boundary;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(sb.ToString()), 0, Encoding.UTF8.GetByteCount(sb.ToString()));
dataStream.Write(buffer, 0, buffer.Length);
dataStream.Write(Encoding.UTF8.GetBytes(LINE_END + PREFIX + boundary + PREFIX + LINE_END), 0, Encoding.UTF8.GetByteCount(LINE_END + PREFIX + boundary + PREFIX + LINE_END));
dataStream.Close();

WebResponse webResponse = request.GetResponse();
Stream newStream = webResponse.GetResponseStream();

StreamReader rdr = new StreamReader(newStream);
var result = rdr.ReadToEnd();
return result;
}

C# 模拟Form表单上传文件方法

标签:

原文地址:http://www.cnblogs.com/TotoVlen/p/4709979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!