利用HttpWebRequest上传文件

参考代码:

http://www.cnblogs.com/charles001/articles/1031515.html 

1.给定UploadUrl地址

 

View Code
  public void UploadFile(Stream postedStream, string fileName,
string uploadURL, string fileGroup, string fileType,
string specialPath, string userName, string uploadType)
{
if (String.IsNullOrEmpty(uploadURL))
{
throw new Exception("上传路径为空!");
}

HttpWebRequest webRequest = WebRequest.Create(uploadURL) as HttpWebRequest;
if (webRequest == null)
{
throw new Exception(String.Format("{0},地质创建失败!", uploadURL));
}

webRequest.Method = WebRequestMethods.Http.Post;

WebProxy proxy = new WebProxy();
proxy.UseDefaultCredentials = true;
webRequest.Proxy = proxy;

webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postedStream.Length;
webRequest.Headers.Add("FileGroup", fileGroup);
webRequest.Headers.Add("FileType", fileType);
webRequest.Headers.Add("UploadType", uploadType);
webRequest.Headers.Add("FileName", System.Web.HttpUtility.UrlEncode(fileName));
webRequest.Headers.Add("UserName", userName);
webRequest.Headers.Add("SpecialFolderPath", System.Web.HttpUtility.UrlEncode(specialPath));

using (Stream responstStream = webRequest.GetRequestStream())
{

const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = postedStream.Read(buffer, 0, bufferLen)) > 0)
{
responstStream.Write(buffer, 0, count);
}
responstStream.Close();
responstStream.Close();
}

try
{
webRequest.GetResponse().Close();
}
catch (WebException ex)
{
HttpWebResponse response = ex.Response as HttpWebResponse;
if (response != null)
{
throw new WebException(response.StatusDescription, ex);
}
throw ex;
}
catch (Exception exception)
{
throw exception;
}
}

 

mvc前台接受传递过来的文件

View Code
public ActionResult About()
{

var keys = Request.Headers.Keys;
Stream stream = Request.InputStream;

var FileGroup = Request.Headers["FileGroup"];
var FileType = Request.Headers["FileType"];
var UploadType = Request.Headers["UploadType"];
var FileName = Request.Headers["FileName"];
var UserName = Request.Headers["UserName"];
var SpecialFolderPath = Request.Headers["SpecialFolderPath"];
UploadFileModel fileModel = new UploadFileModel
{
FileGroup = FileGroup,
FileLength = 11,
UploadType = UploadType,
FileName = System.Web.HttpUtility.UrlDecode(FileName),
FileType = FileType,
UserName = UserName
};

String savePath = Server.MapPath("~/Content/File");
// String path = savePath + FileName;
string filePath = Path.Combine(savePath, FileName);
try
{


StreamReader sr = new StreamReader(stream);
Stream sw = new FileStream(filePath, FileMode.Create,FileAccess.Write,FileShare.None);
const int bufferLen = 65000;
byte []buff = new byte[bufferLen];
int index = 0;
while ((index = stream.Read(buff, 0, bufferLen)) > 0)
{
sw.Write(buff, 0, index);
}
sw.Flush();
sw.Close();
}
catch (Exception)
{

;
}
return View(fileModel);
}




posted @ 2012-04-10 11:23  玄魄冰  阅读(781)  评论(0编辑  收藏  举报