如何在collection 获取 mvc 获取httpcontextt

asp.net获取HTML表单File中的路径的方法
转载 & & 作者:
这篇文章主要介绍了asp.net怎么获取HTML表单File中的路径,需要的朋友可以参考下
代码如下:#region 上传文件到数据库和服务器 public void FN_UpFiles() { //遍历File表单元素 HttpFileCollection files = HttpContext.Current.Request.F try { for (int iFile = 0; iFile & files.C iFile++) { //检查文件扩展名字 HttpPostedFile postedFile = files[iFile]; string fileName = "";//定义文件名 //string fileExtension = ""; fileName = Path.GetFileName(postedFile.FileName);//得到上传文件的完整名称 即文件名+后缀名 int index = fileName.IndexOf("."); string FileType = fileName.Substring(index).ToLower();//截取文件后缀名 //FileTypeImg = "../FileTypeimg/" + hz + ".gif"; Guid fileGuid = Guid.NewGuid();//生成新的文件名称 以GUID命名防止文件名相同 string NewFileName = fileGuid.ToString();//新的文件名 NewFileName = NewFileName + FileT//新的文件名+后缀名 if (postedFile.ContentLength & 2097151 * 1024)//判断是否大于配置文件中的上传文件大小 { Page.RegisterStartupScript("提示", "&script language='javascript'&alert('对不起您的上传资源过大!');&/script&");
} else { if (fileName != "")//如果文件名不为空 { try { //文件虚拟路径 string strpath = System.Web.HttpContext.Current.Server.MapPath("~/Upload/") + NewFileN try { NRModel.File model = new NRModel.File(); NRBLL.File bf = new NRBLL.File(); Guid guid1 = Guid.NewGuid(); Guid guid2 = new Guid(FolderId); Guid guid3 = Guid.NewGuid(); Guid guid4 = Guid.NewGuid(); model.Fileid = guid1; model.Folderid = guid2; model.Filepath = model.FileNam = fileN model.FileSize = postedFile.ContentL model.Decription = TextArea1.Value.ToString(); model.CreateOn = DateTime.N model.CreateBy = guid3; model.ModefyBy = guid4; if (bf.FN_AddNewRes(model) & 0) { NR.Error.Log.LogType("上传资源" + fileName + "成功!" + "服务器路径:" + strpath); //保存文件到指定目录(虚拟目录) postedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/Upload/") + NewFileName); //Page.RegisterStartupScript("提示", "&script language='javascript'&alert('上传成功!');self.opener.location.reload();window.close();&/script&"); AlertMsg("上传成功!"); } } catch (Exception ex) { NR.Error.Log.LogType(ex.ToString()); } } catch (Exception ex) { NR.Error.Log.LogType(ex.ToString()); } } else { Response.Write("上传文件不能为空!"); NR.Error.Log.LogType("文件不能为空!"); } } } } catch (System.Exception ex) { NR.Error.Log.LogType(ex.ToString()); } } #endregion
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具总结:ASP.NET MVC5中通过HttpWebRequest上传图片文件到服务器_蓝狐软件工作室
ASP.NET MVC
Posted By : 蓝狐
其实使用网页上传图片或者其它文件时,表单为我们简化了文件的上传的过程。但是有时我们想把前台上传过来的文件在保存到服务器的时候同时提交到另外一个服务器地址并保存起来。要实现这个功能要利用HttpWebRequest模拟网页的表单提交过程。今天我就来分享一下我在ASP.NET 5中通过HttpWebRequest上传文件到服务器的实现方案。
一、传统的网页上传文件方法
首先我们来看看传统的表单提交过程。
当我们都是通过表单来上传文件。前台html代码:
&form enctype="multipart/form-data" action="/Upload/UploadPic" method="post" id="UploadForm"&
&div style="padding:15 text-align:"&
&input type="file" style="margin-bottom:10" name="UploadImage" id="UploadImage"&
&input type="submit" class="btn btn-primary" value="上传"&
把form标签的加一个enctype="multipart/form-data"属性,后台可以通过Request.Files获取到前台上传过来的文件,并且可以用file.SaveAs(fileFullPath)把文件保存下来。
二、使用HttpWebRequest上传文件到服务器
using System.Collections.G
using System.Collections.S
using System.IO;
using System.;
using System.N
using System.T
using System.Threading.T
namespace Lanhu.Core
public class NetHelper
/// &summary&
/// 通过HttpWebRequest上传文件到服务器
/// &/summary&
/// &param name="url"&上传地址&/param&
/// &param name="file"&文件所有位置&/param&
/// &param name="paramName"&表单参数名&/param&
/// &param name="contentType"&文件的contentType&/param&
/// &param name="nvc"&其他参数集合&/param&
/// &returns&&/returns&
public static string UploadFileByHttpWebRequest(string url, string file, string paramName, string contentType, NameValueCollection nvc)
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form- boundary=" +
wr.Method = "POST";
wr.KeepAlive =
wr.Credentials = System.Net.CredentialCache.DefaultC
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form- name=\"{0}\"\r\n\r\n{1}";
if (nvc != null)
foreach (string key in nvc.Keys)
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form- name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
rs.Write(buffer, 0, bytesRead);
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp =
var result = "";
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//成功返回的結果
result = reader2.ReadToEnd();
catch (Exception ex)
if (wresp != null)
wresp.Close();
上面使用HttpWebRequest采用二进制流的形式模拟一个表单提交过程,这样后台也可以采用传统形式获取传过来的文件。
三、ASP.NET MVC5中一个完整的接收图片文件的Controller
using Newtonsoft.J
using System.C
using System.Collections.G
using System.D
using System.D
using System.G
using System.IO;
using System.L
using System.T
using System.Text.RegularE
using System.W
using System.Web.M
namespace Lanhu.Admin.Controllers
public class UploadController : Controller
private string FilePhysicalPath = string.E
private string FileRelativePath = string.E
#region Private Methods
/// &summary&
/// 检查是否为合法的上传图片
/// &/summary&
/// &param name="_fileExt"&&/param&
/// &returns&&/returns&
private string CheckImage(HttpPostedFileBase imgfile)
string allowExt = ".gif.jpg.png";
string fileName = imgfile.FileN
FileInfo file = new FileInfo(fileName);
string imgExt = file.E
Image img = IsImage(imgfile);
string errorMsg = fileName + ":";
if (img == null)
errorMsg = "文件格式错误,请上传gif、jpg、png格式的图片";
return errorM
if (allowExt.IndexOf(imgExt.ToLower()) == -1)
errorMsg = "请上传gif、jpg、png格式的图片;";
//if (imgfile.ContentLength & 512 * 1024)
errorMsg += "图片最大限制为0.5Mb;";
//if (img.Width & 20 || img.Width & 480 || img.Height & 20 || img.Height & 854)
errorMsg += "请上传正确尺寸的图片,图片最小为20x20,最大为480*854。";
if (errorMsg == fileName + ":")
return "";
return errorM
/// &summary&
/// 验证是否为真正的图片
/// &/summary&
/// &param name="file"&&/param&
/// &returns&&/returns&
private Image IsImage(HttpPostedFileBase file)
Image img = Image.FromStream(file.InputStream);
private string NewFileName(string fileNameExt)
return DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileNameE
//return Guid.NewGuid().ToString() + fileNameE
private UploadImgResult UploadImage(HttpPostedFileBase file)
UploadImgResult result = new UploadImgResult();
string fileNameExt = (new FileInfo(file.FileName)).E
//string saveName = GetImageName() + fileNameE
//获得要保存的文件路径
String newFileName = NewFileName(fileNameExt);
String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
FilePhysicalPath += ymd + "/";
FileRelativePath += ymd + "/";
String fileFullPath = FilePhysicalPath + newFileN
if (!Directory.Exists(FilePhysicalPath))
Directory.CreateDirectory(FilePhysicalPath);
file.SaveAs(fileFullPath);
string relativeFileFullPath = FileRelativePath + newFileN
result.Result = 1;
result.msg = relativeFileFullP
catch (Exception ex)
result.Result = 3;
result.msg = ex.M
private void showError(string message)
Hashtable hash = new Hashtable();
hash["error"] = 1;
hash["message"] =
Response.AddHeader("Content-Type", "text/ charset=UTF-8");
Response.Write(JsonConvert.SerializeObject(hash));
Response.End();
#endregion
[HttpPost]
public string UploadPic()
Response.ContentType = "text/plain";
List&UploadImgResult& results = new List&UploadImgResult&();
FileRelativePath = System.Configuration.ConfigurationManager.AppSettings["UploadProductImgPath"];
FilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath(FileRelativePath);
if (!Directory.Exists(FilePhysicalPath))
Directory.CreateDirectory(FilePhysicalPath);
string saveFileResult = string.E
HttpFileCollectionBase files = (HttpFileCollectionBase)Request.F
for (int i = 0; i & files.C i++)
HttpPostedFileBase file = files[i];
UploadImgResult result =
string checkResult = CheckImage(file);
if (string.IsNullOrEmpty(checkResult))
result = UploadImage(file);
result = new UploadImgResult();
result.Result = 2;
result.msg = checkR
results.Add(result);
string json = JsonConvert.SerializeObject(results);
private void HandleWaterMark(string fileFullPath)
bool isWaterMask = Request.Form["watermask"] == "1";
if (isWaterMask)
string waterurl = Request.MapPath("/Content/water.png");
//CommonHelper.MakeWatermark(fileFullPath, waterurl, fileFullPath, 4, 95);
public string FileManagerJson()
String aspxUrl = Request.Path.Substring(0, Request.Path.LastIndexOf("/") + 1);
////根目录路径,相对路径
//String rootPath = "../attached/";
////根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
//String rootUrl = aspxUrl + "../attached/";
//根目录路径,相对路径
String rootPath = System.Configuration.ConfigurationManager.AppSettings["UploadDir"];
//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
String rootUrl = System.Configuration.ConfigurationManager.AppSettings["UploadDir"];
//图片扩展名
String fileTypes = "gif,jpg,jpeg,png,bmp";
String currentPath = "";
String currentUrl = "";
String currentDirPath = "";
String moveupDirPath = "";
String dirPath = Server.MapPath(rootPath);
String dirName = Request.QueryString["dir"];
if (!String.IsNullOrEmpty(dirName))
if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
return "Invalid Directory name.";
dirPath += dirName + "/";
rootUrl += dirName + "/";
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//根据path参数,设置各路径和URL
String path = Request.QueryString["path"];
path = String.IsNullOrEmpty(path) ? "" :
if (path == "")
currentPath = dirP
currentUrl = rootU
currentDirPath = "";
moveupDirPath = "";
currentPath = dirPath +
currentUrl = rootUrl +
currentDirPath =
moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
//排序形式,name or size or type
String order = Request.QueryString["order"];
order = String.IsNullOrEmpty(order) ? "" : order.ToLower();
//不允许使用..移动到上一级目录
if (Regex.IsMatch(path, @"\.\."))
Response.Write("Access is not allowed.");
Response.End();
//最后一个字符不是/
if (path != "" && !path.EndsWith("/"))
Response.Write("Parameter is not valid.");
Response.End();
//目录不存在或不是目录
if (!Directory.Exists(currentPath))
Response.Write("Directory does not exist.");
Response.End();
//遍历目录取得文件信息
string[] dirList = Directory.GetDirectories(currentPath);
string[] fileList = Directory.GetFiles(currentPath);
switch (order)
case "size":
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new SizeSorter());
case "type":
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new TypeSorter());
case "name":
Array.Sort(dirList, new NameSorter());
Array.Sort(fileList, new NameSorter());
Hashtable result = new Hashtable();
result["moveup_dir_path"] = moveupDirP
result["current_dir_path"] = currentDirP
result["current_url"] = currentU
result["total_count"] = dirList.Length + fileList.L
List&Hashtable& dirFileList = new List&Hashtable&();
result["file_list"] = dirFileL
for (int i = 0; i & dirList.L i++)
DirectoryInfo dir = new DirectoryInfo(dirList[i]);
Hashtable hash = new Hashtable();
hash["is_dir"] =
hash["has_file"] = (dir.GetFileSystemInfos().Length & 0);
hash["filesize"] = 0;
hash["is_photo"] =
hash["filetype"] = "";
hash["filename"] = dir.N
hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
dirFileList.Add(hash);
for (int i = 0; i & fileList.L i++)
FileInfo file = new FileInfo(fileList[i]);
Hashtable hash = new Hashtable();
hash["is_dir"] =
hash["has_file"] =
hash["filesize"] = file.L
hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) &= 0);
hash["filetype"] = file.Extension.Substring(1);
hash["filename"] = file.N
hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
dirFileList.Add(hash);
Response.AddHeader("Content-Type", "application/ charset=UTF-8");
//Response.Write(JsonConvert.SerializeObject(result));
//Response.End();
return JsonConvert.SerializeObject(result);
#region Model
public class UploadImgResult
public int Result { } //1成功,2失败,3异常
public string msg { }
public class NameSorter : IComparer
public int Compare(object x, object y)
if (x == null && y == null)
if (x == null)
return -1;
if (y == null)
FileInfo xInfo = new FileInfo(x.ToString());
FileInfo yInfo = new FileInfo(y.ToString());
return xInfo.FullName.CompareTo(yInfo.FullName);
public class SizeSorter : IComparer
public int Compare(object x, object y)
if (x == null && y == null)
if (x == null)
return -1;
if (y == null)
FileInfo xInfo = new FileInfo(x.ToString());
FileInfo yInfo = new FileInfo(y.ToString());
return xInfo.Length.CompareTo(yInfo.Length);
public class TypeSorter : IComparer
public int Compare(object x, object y)
if (x == null && y == null)
if (x == null)
return -1;
if (y == null)
FileInfo xInfo = new FileInfo(x.ToString());
FileInfo yInfo = new FileInfo(y.ToString());
return xInfo.Extension.CompareTo(yInfo.Extension);
#endregion
这个处理上传图片的Controller中UploadPic就是对外公开的Action。要使用这个ASP.NET MVC5的Action上传图片你可以采用网页的表单也可以用上面我讲的用HttpWebRequest。
最后,我们来看看怎么使用我们头面封装的NetHelper把前台上传过来的文件在保存到服务器的时候同时提交到另外一个服务器地址并保存起来。
[HttpPost]
public string UploadPic()
string json = "";
Response.ContentType = "text/plain";
List&UploadImgResult& results = new List&UploadImgResult&();
FileRelativePath = System.Configuration.ConfigurationManager.AppSettings["UploadProductImgPath"];
FilePhysicalPath = System.Web.HttpContext.Current.Server.MapPath(FileRelativePath);
if (!Directory.Exists(FilePhysicalPath))
Directory.CreateDirectory(FilePhysicalPath);
string saveFileResult = string.E
HttpFileCollectionBase files = (HttpFileCollectionBase)Request.F
for (int i = 0; i & files.C i++)
HttpPostedFileBase file = files[i];
UploadImgResult result =
string checkResult = CheckImage(file);
if (string.IsNullOrEmpty(checkResult))
//上传到本地并返回保存到所在服务器的相对地址
result = UploadImage(file);
//将图片上传到远程的服务器
json=NetHelper.UploadFileByHttpWebRequest(Lanhusoft.Core.AppConfigHelper.ImageHost+"/Upload/UploadPic", Server.MapPath(result.msg), "uploadFileName", file.ContentType, null);
//把远程服务器返回的保存图片相对地址替换成http开头的绝对地址
results = JsonConvert.DeserializeObject&List&UploadImgResult&&(json);
//处理文件在远程服务器和本地服务器路径不一致的问题
& & & & & & & & & &
FileInfo fi = new FileInfo(Server.MapPath(result.msg));
& & & & & & & & & &
var dir=Path.GetDirectoryName(Server.MapPath(results[0].msg));
& & & & & & & & & &
if (!Directory.Exists(dir))
& & & & & & & & & & & &
Directory.CreateDirectory(dir);
& & & & & & & & & &
fi.MoveTo(Server.MapPath(results[0].msg));
& & & & & & & & & &&
& & & & & & & & & &
result = new UploadImgResult();
result.Result = 2;
result.msg = checkR
results.Add(result);
json = JsonConvert.SerializeObject(results);
本站文章除注明转载外,均为本站原创或翻译,欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,共创和谐网络环境。
转载请注明:文章转载自: >>
本文标题:总结:ASP.NET MVC5中通过HttpWebRequest上传图片文件到服务器
本文地址:http://www.lanhusoft.com/Article/406.html
本科学历,蓝狐软件工作室创始人。2009年开始从事软件开发行业,从事软件开发互朕网7年以上,3年以上项目管理和架构设计经验,具有丰富的电子商务行业的移动和Web应用的架构设计和开发经验。参与过高并发、高可用、分布式系统设计,熟悉SOA架构设计,有敏捷开发经验。熟悉.NET和Java EE相关技术和框架,熟悉Linux、Windows、Nginx、Mysql等服务器的部署和优化。熟悉主流的开发语言,擅长SQL Server、mysql、Oracle等主流数据库,通过了Oracle OCP 11g认证,有丰富的数据库性能优化和设计经验。独立开发了多个人作品:蓝狐seo管理系统、seo关键词按天计费系统、蓝狐软件工作室门户等。曾在多家移动互联网担当核心技术研发和管理工作,同时承担关键技术难点攻关和设计高性能的技术架构。把握平台的技术发展方向,对技术发展及时提出指导性意见。在提高平台的稳定性、性能、质量等方面做出了重要贡献。目前专职于为企业提供优质的信息化建设服务,其中不限于系统、软件定制开发和高端网站建设。
文章写的不错,这个可以用在CKEditor编辑器上传图片么?
发表成功!下次自动登录
现在的位置:
& 综合 & 正文
几个http请求相关的函数 HttpWebRequest: Post , G PostAndRedirect
几个http请求相关的函数 HttpWebRequest: Post , G PostAndRedirect
1、 通过HttpWebRequest发起一个Post请求,并获取返回数据
使用指定编码格式发送一个POST请求,并通过约定的编码格式获取返回的数据
/// &summary&
/// 使用指定编码格式发送一个POST请求,并通过约定的编码格式获取返回的数据
/// &/summary&
/// &param name="url"&请求的url地址&/param&
/// &param name="parameters"&请求的参数集合&/param&
/// &param name="reqencode"&请求的编码格式&/param&
/// &param name="resencode"&接收的编码格式&/param&
/// &returns&&/returns&
public static string SendPostRequest(string url, NameValueCollection parameters, Encoding reqencode, Encoding resencode)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "post";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder parassb = new StringBuilder();
foreach (string key in parameters.Keys)
if (parassb.Length & <span style="color: #)
parassb.Append("&");
parassb.AppendFormat("{0}={1}", key, parameters[key]);
byte[] data = reqencode.GetBytes(parassb.ToString());
Stream reqstream = req.GetRequestStream();
reqstream.Write(data, <span style="color: #, data.Length);
reqstream.Close();
string result = String.E
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), resencode))
result = reader.ReadToEnd();
2、通过HttpWebRequest发起一个Get请求,并获取返回数据
HttpWebRequest 发送一个GET请求
* 需要引用如下namespace
* using System.R
* using System.T
* using System.N
* using System.IO;
/// &summary&
/// HttpWebRequest 发送一个GET请求
/// &/summary&
/// &param name="url"&请求的url地址&/param&
/// &param name="parameters"&请求的参数集合&/param&
/// &param name="reqencode"&请求的编码格式&/param&
/// &param name="resencode"&接收的编码格式&/param&
/// &returns&&/returns&
public static string SendGetRequest(string baseurl, NameValueCollection parameters, Encoding reqencode, Encoding resencode)
StringBuilder parassb = new StringBuilder();
foreach (string key in parameters.Keys)
if (parassb.Length & <span style="color: #)
parassb.Append("&");
parassb.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key, reqencode), HttpUtility.UrlEncode(parameters[key], reqencode));
if (parassb.Length & <span style="color: #)
baseurl += "?" +
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);
req.Method = "GET";
req.MaximumAutomaticRedirections = <span style="color: #;
req.Timeout = <span style="color: #00;
string result = String.E
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream(), resencode))
result = reader.ReadToEnd();
3、通过编程的方式实现Post提交请求并重定向至新的URL地址
Post请求并且重定向
/// &summary&
/// Post请求并且重定向
/// &/summary&
/// &param name="url"&&/param&
/// &param name="parameters"&&/param&
/// &param name="context"&&/param&
public static void PostAndRedirect(string url, NameValueCollection parameters, HttpContext context)
StringBuilder script = new StringBuilder();
script.AppendFormat("&form name=redirpostform action='{0}' method='post'&", url);
foreach (string key in parameters.Keys)
script.AppendFormat("&input type='hidden' name='{0}' value='{1}'&",
key, parameters[key]);
script.Append("&/form&");
script.Append("&script language='javascript'&redirpostform.submit();&/script&");
context.Response.Write(script);
context.Response.End();
【上篇】【下篇】}

我要回帖

更多关于 httpcontext 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信