C#--图片上传(PC端和APP)保存及 跨域上传说明
手动跨域操作文件 补录:跨域访问文件夹文件是一种常见的需求,下面主要介绍的的通过代码使用具有权限账号的人来达到跨域操作文件的能力。 现在补充一下普通的一些需求场景,今天就遇到了一种需要经常需要登录远程服务器来部署文件的情况? ?但是远程服务器限制了登录人数同时在线2人,每次我想发布新版本到测试服务器时都需要等别人断开连接后才可以。 ?那么学了这个知识后,我们就可以在我们本地就可以远程操作文件的删除,更新。 也很简单,下面的代码全不管,直接自己手动添加一个网络驱动器(驱动盘随机),填写上需要影射的服务器文件路径,勾选使用其他票据登陆,使用带有操作权限的账号就可以完整服务器文件夹影射到本地网络磁盘的需求了,这时我们就可以通过这个网络驱动器来进行想要的操作了,是不是很棒?!!!如下图: 我要影射的服务器路径为:10.0.9.244Seagll2WebSiteWebApiYuanXinApi ? 将该路径粘贴到文件夹输入框中即可。 ? 通过代码跨域操作文件: A-PC端: 1-页面--multiple是控制单张还是多张图片上传 <input id="BusRoute" type="file" class="btn btn-default btn-lg" style="height:34px;padding-top:5px;padding-bottom:5px;" multiple /> 2-后台获取图片文件: HttpFileCollection pcFileColl = HttpContext.Current.Request.Files; 3-保存示例: #region 创建目录 //完整存储路径 string completeUrl = ""; 相对等级路径 string relativeUrl = ; string saveTempPath = "~/Resources/Pic"; string picUploadPath = HttpContext.Current.Server.MapPath(saveTempPath); 添加根目录 completeUrl = @"10.0.8.52YuanXinFilesOffice"; ; 添加一级目录 string relativeOneUrl = DateTime.Now.Year.ToString(); completeUrl += "" + relativeOneUrl; relativeUrl += relativeOneUrl; if (!Directory.Exists(completeUrl)) { Directory.CreateDirectory(completeUrl); } 添加二级目录 string relativeTwoUrl = DateTime.Now.Month.ToString(); completeUrl += relativeTwoUrl; relativeUrl += relativeTwoUrl; #endregion //保存 HttpFileCollection picColl = picModel.PcFileColl; for (var i = 0; i < picColl.Count; i++) { HttpPostedFile file = picColl[i]; //保存图片 保存至指定目录 file.SaveAs(completeUrl + fileName); } B-APP: 前端页面长什么样不管了,后台拿到的是base64的字符串集合. 1-保存示例: Directory.Exists(completeUrl)) { Directory.CreateDirectory(completeUrl); } #endregion 保存 byte[] bytes = Convert.FromBase64String(strPic.picCode); MemoryStream memStream = new MemoryStream(bytes); BinaryFormatter binFormatter = BinaryFormatter(); System.Drawing.Bitmap map = Bitmap(memStream); Image image = (Image)map; string imageName = Guid.NewGuid().ToString(N); 保存图片 image.Save(completeUrl + " + imageName + ." + strPic.picType); 保存图片 C-跨域保存问题: 跨域的常见场景如下图所示:我们通过电脑的网络影射,连接到所需要的目录,这里添加上拥有权限的人员账号即可访问目标文件夹,那么使用C#代码如何获得访问权限呢? ? ? 要获取以上访问权限,需要引用一个类和添加一些简单代码: 1-访问代码: /// <summary> /// 通过指定用户执行上次图片操作 </summary> <param name="uploadAction"></param> public void UploadFileByUser(Action uploadAction) { 参考类:D:SourceCodeMCSFramework 2.DevelopMobileWebAppYuanXinServicesFileUploadServiceControllersUploadController.cs 无法通过权限认证--只能通过外网访问 try { var ip = 10.0.8.52; var domain = sinooceanlandvar username = ConfigurationManager.AppSettings[uploadUserName"].ToString(); 配置的用户名 var pwd = ConfigurationManager.AppSettings[uploadPassword"].ToString(); 配置的密码 var root = ConfigurationManager.AppSettings[uploadRootPath"].ToString(); 配置的文件根路径 using (NetworkShareAccesser.Access(ip,domain,username,pwd)) 建立连接 { uploadAction(); 图片保存代码 } } catch (System.Exception e) { } } 2-必须类: class NetworkShareAccesser : IDisposable { private string _remoteUncName; _remoteComputerName; RemoteComputerName { getreturn this._remoteComputerName; } setthis._remoteComputerName = value; this._remoteUncName = " + ._remoteComputerName; } } UserName { ; ; } Password { ; } #region Consts const int RESOURCE_CONNECTED = 0x00000001; int RESOURCE_GLOBALNET = 0x00000002int RESOURCE_REMEMBERED = 0x00000003; int RESOURCETYPE_ANY = 0x00000000int RESOURCETYPE_DISK = int RESOURCETYPE_PRINT = int RESOURCEDISPLAYTYPE_GENERIC = int RESOURCEDISPLAYTYPE_DOMAIN = int RESOURCEDISPLAYTYPE_SERVER = int RESOURCEDISPLAYTYPE_SHARE = int RESOURCEDISPLAYTYPE_FILE = 0x00000004int RESOURCEDISPLAYTYPE_GROUP = 0x00000005int RESOURCEUSAGE_CONNECTABLE = int RESOURCEUSAGE_CONTAINER = ; int CONNECT_INTERACTIVE = 0x00000008int CONNECT_PROMPT = 0x00000010int CONNECT_REDIRECT = 0x00000080int CONNECT_UPDATE_PROFILE = int CONNECT_COMMANDLINE = 0x00000800int CONNECT_CMD_SAVECRED = 0x00001000int CONNECT_LOCALDRIVE = 0x00000100#endregion #region Errors int NO_ERROR = 0int ERROR_ACCESS_DENIED = 5int ERROR_ALREADY_ASSIGNED = 85int ERROR_BAD_DEVICE = 1200int ERROR_BAD_NET_NAME = 67int ERROR_BAD_PROVIDER = 1204int ERROR_CANCELLED = 1223int ERROR_EXTENDED_ERROR = 1208int ERROR_INVALID_ADDRESS = 487int ERROR_INVALID_PARAMETER = 87int ERROR_INVALID_PASSWORD = 1216int ERROR_MORE_DATA = 234int ERROR_NO_MORE_ITEMS = 259int ERROR_NO_NET_OR_BAD_PATH = 1203int ERROR_NO_NETWORK = 1222int ERROR_BAD_PROFILE = 1206int ERROR_CANNOT_OPEN_PROFILE = 1205int ERROR_DEVICE_IN_USE = 2404int ERROR_NOT_CONNECTED = 2250int ERROR_OPEN_FILES = 2401#region PInvoke Signatures [DllImport(Mpr.dll)] static extern int WNetUseConnection( IntPtr hwndOwner,NETRESOURCE lpNetResource, lpPassword,1)"> lpUserID,1)"> dwFlags,1)"> lpAccessName,1)"> lpBufferSize,1)"> lpResult ); [DllImport( WNetCancelConnection2( lpName,1)">bool fForce ); [StructLayout(LayoutKind.Sequential)] NETRESOURCE { int dwScope = int dwType = int dwDisplayType = int dwUsage = string lpLocalName = string lpRemoteName = string lpComment = string lpProvider = #endregion Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials <param name="remoteComputerName"></param> <returns></returns> static NetworkShareAccesser Access( remoteComputerName) { NetworkShareAccesser(remoteComputerName); } Creates a NetworkShareAccesser for the given computer name using the given domain/computer name,username and password <param name="domainOrComuterName"></param> <param name="userName"></param> <param name="password"></param> string remoteComputerName,string domainOrComuterName,1)">string userName,1)"> password) { NetworkShareAccesser(remoteComputerName,domainOrComuterName + userName,password); } Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputernameUsername) and password private NetworkShareAccesser( remoteComputerName) { RemoteComputerName = remoteComputerName; this.ConnectToShare(this._remoteUncName,1)">null,1)">true); } password) { RemoteComputerName = remoteComputerName; UserName = userName; Password = password; this.UserName,1)">this.Password,1)">falsevoid ConnectToShare(string remoteUnc,1)">string username,1)">string password,1)"> promptUser) { NETRESOURCE nr = NETRESOURCE { dwType = RESOURCETYPE_DISK,lpRemoteName = remoteUnc }; result; if (promptUser) { result = WNetUseConnection(IntPtr.Zero,nr,"",CONNECT_INTERACTIVE | CONNECT_PROMPT,1)">null); } else { result = WNetUseConnection(IntPtr.Zero,password,1)">0,1)">); } if (result != NO_ERROR) { throw Win32Exception(result); } } void DisconnectFromShare( remoteUnc) { int result = WNetCancelConnection2(remoteUnc,CONNECT_UPDATE_PROFILE,1)">); Win32Exception(result); } } Performs application-defined tasks associated with freeing,releasing,or resetting unmanaged resources. <filterpriority>2</filterpriority> Dispose() { this.DisconnectFromShare(._remoteUncName); } } ? D--附件类展示(仅供参考): <summary> 附件表 </summary> [ORTableMapping(office.Attachment)] AttachmentModel { 主键ID <summary> [ORFieldMapping(ID",PrimaryKey = string ID { get; ; } 资源ID ResourceIDstring ResourceID { 相对路径 RelativePathstring RelativePath { 显示路径 </summary> ShowPath { string path = AttachmentModelAdapter.Instance.downLoadRootUrl + this.RelativePath + /this.FileName + .FileType; return path; } } 文件名称 FileNamestring FileName { 文件类型 FileTypestring FileType { 创建时间 CreateTimepublic DateTime CreateTime { 有效性 ValidStatusbool ValidStatus { ; } } class AttachmentModelCollection : EditableDataObjectCollectionBase<AttachmentModel> { } class AttachmentModelAdapter : BaseAdapter<AttachmentModel,AttachmentModelCollection> { static AttachmentModelAdapter Instance = AttachmentModelAdapter(); string ConnectionString = ConnectionNameDefine.YuanXinBusiness; 上传文件路径(如果路径含有相对路径标记~ 则使用Server获取完整路径,否则获取配置路径) string upLoadRootUrl = ConfigurationManager.AppSettings["].Contains(~") ? HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["]) : ConfigurationManager.AppSettings[]; 下载文件路径 string downLoadRootUrl = ConfigurationManager.AppSettings[downLoadRootPath是否上传到本地服务器 bool IsUploadLocalService = ConfigurationManager.AppSettings[IsUploadLocalService"] == true" ? true : public AttachmentModelAdapter() { BaseConnectionStr = .ConnectionString; } 设置用户权限通过远程文件增删 if (IsUploadLocalService == ) { var ip = ConfigurationManager.AppSettings[uploadServiceIP上传的服务器IP--10.0.8.52 ; 配置的用户名--v-zhaotzh 配置的密码--pass@123 var root = upLoadRootUrl; 配置的文件根路径--~/Resources/Pic { uploadAction(); } } { uploadAction(); (System.Exception e) { } } #region 文件保存 保存附件集合 SaveFileColl(AttachmentModelCollection acoll) { StringBuilder sql = StringBuilder(); acoll.ForEach(ac => { sql.Append(ORMapping.GetInsertSql<AttachmentModel>(ac,TSqlBuilder.Instance,1)">"") + ;); }); int result = ViewBaseAdapter<AttachmentModel,List<AttachmentModel>>.Instance.RunSQLByTransaction(sql.ToString(),ConnectionNameDefine.YuanXinForDBHelp); result; } 保存图片至服务器及将数据入库 <param name="picModel"></param> SavePicColl(PictureHelp picModel) { UploadFileByUser(() =>#region 创建目录 完整存储路径 相对等级路径 ; 添加根目录 completeUrl = upLoadRootUrl; 添加一级目录 DateTime.Now.Year.ToString(); completeUrl += relativeOneUrl; relativeUrl += relativeOneUrl; Directory.Exists(completeUrl)) { Directory.CreateDirectory(completeUrl); } 添加二级目录 DateTime.Now.Month.ToString(); completeUrl += relativeTwoUrl; relativeUrl += relativeTwoUrl; #endregion AttachmentModelCollection modelColl = AttachmentModelCollection(); #region 来源于APP if (picModel.AppPicColl != null && picModel.AppPicColl.Count > ) { List<AppPicHelp> strPicColl = picModel.AppPicColl; foreach (var strPic in strPicColl) { Convert.FromBase64String(strPic.picCode); MemoryStream memStream = MemoryStream(bytes); BinaryFormatter binFormatter = BinaryFormatter(); System.Drawing.Bitmap map = Bitmap(memStream); Image image = (Image)map; 保存图片 "); 图片重命名 image.Save(completeUrl + 保存图片 AttachmentModel model = AttachmentModel() { ID = Guid.NewGuid().ToString(),CreateTime = DateTime.Now,FileName = imageName,FileType = strPic.picType,RelativePath = relativeUrl,ResourceID = picModel.ResourceID,ValidStatus = }; modelColl.Add(model); } } #endregion #region 来源于PC端 来源于PC端 else if (picModel.PcFileColl != null && picModel.PcFileColl.Count > ) { HttpFileCollection picColl = picModel.PcFileColl; 入库 ) { HttpPostedFile file = picColl[i]; string[] oldFileNameList = file.FileName.Split(''); string fileName = oldFileNameList[0] + _" + DateTime.Now.ToString(HH-mm-ss") + " + Guid.NewGuid().ToString(").Substring(5) + " + oldFileNameList[1]; string[] newFileNameList = fileName.Split(); 保存图片 保存至指定目录 file.SaveAs(completeUrl + fileName); AttachmentModel model = AttachmentModel { ID = System.Guid.NewGuid().ToString(,FileName = newFileNameList[],FileType = newFileNameList[ picModel.ResourceID }; modelColl.Add(model); } } 图片数据入库 AttachmentModelAdapter.Instance.SaveFileColl(modelColl); }); } 删除会议圈下图片文件及相关数据 <param name="momentID"></param> void DelPicColl( momentID) { AttachmentModelCollection coll = AttachmentModelAdapter.Instance.Load(m => m.AppendItem(删除本服务器图片 ) { coll.ForEach(c => { File.Delete(c.ShowPath); }); } 删除其他服务器图片 { UploadFileByUser(() => { coll.ForEach(c => { File.Delete(c.ShowPath); }); }); } 删除数据 Delete(m => m.AppendItem(#region 图片帮助类 PictureHelp { pc上传图片集合 public HttpFileCollection PcFileColl { app上传图片集合 public List<AppPicHelp> AppPicColl { AppPicHelp { base64字节 string picCode { 图片类型(jpg/png/...) string picType { #endregion ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – 共享WCF服务和身份验证的MVC2应用程序(和其
- 在本地部署asp.net mvc4到IIS 7.5
- ASP.Net MVC MvcBuildViews大大增加了编译时间
- 只有内容控件才能直接在包含ASP.NET内容控件的内容页面中
- ASP.NET:获取*真实*原始URL
- ASP.NET MVC中是否有嵌套主页?
- 在asp.net vnext上使用bearer token身份验证刷新令牌
- .net – 什么是类的默认访问修饰符?
- asp.net – HttpMessageHandler与DelegatingHandler
- asp.net – AspNetSession布局渲染器不工作
- 为什么在ASP.NET MVC中使用JsonResult时使用WCF
- asp.net-mvc – ASP.NET MVC如何指定View页面驻留
- asp.net-web-api – 没有IQueryable的OData
- asp.net-mvc – 重置asp.net mvc路由而不重置应用
- asp.net-mvc-3 – 实体框架4.1自动日期
- asp.net-mvc-5 – 依赖注入结构图ASP.NET Identi
- asp.net-mvc – MVC – 强类型视图被破坏
- asp.net-mvc – 具有区域的Url.Action()返回空字
- asp.net-mvc-3 – 从View中访问RouteData.Values
- 使用ASP.NET/SQL Server丢失会话状态