本文介绍了在ASP.NET中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我必须上传文件而不提供我的文件夹的完全权限,其中所有文件都将上传。 我必须使用asp.net中的文件模拟上传文件 当我在网络配置中写入身份impersonate =true时,它会向网站显示错误。 我尝试了什么: < identity impersonate =trueusername =password =/> public partial class Uploadfile :System.Web.UI.Page { public const int LOGON32_LOGON_INTERACTIVE = 2 ; public const int LOGON32_PROVIDER_DEFAULT = 0 ; WindowsImpersonationContext impersonationContext; [DllImport( advapi32.dll)] public static extern int LogonUserA( String lpszUserName, String lpszDomain, 字符串 lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport( advapi32.dll,CharSet = CharSet.Auto,SetLastError = true )] public static extern int DuplicateToken( IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken); [DllImport( advapi32.dll,CharSet = CharSet.Auto ,SetLastError = true )] public static extern bool RevertToSelf(); [DllImport( kernel32.dll,CharSet = CharSet.Auto )] public static extern bool CloseHandle( IntPtr 句柄); private bool ImpersonateUser( String userName, String domain, String 密码) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr .Zero; IntPtr tokenDuplicate = IntPtr .Zero; if (RevertToSelf()) { if (LogonUserA(userName,domain,password,LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token)!= 0 ) { if (DuplicateToken(token, 2 , ref tokenDuplicate)!= 0 ) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext!= null ) { CloseHandle(令牌); CloseHandle(tokenDuplicate); return true ; } } } } 如果(令牌!= IntPtr .Zero) CloseHandle(令牌); if (tokenDuplicate!= IntPtr .Zero) CloseHandle(tokenDuplicate); return false ; } private void UndoImpersonation() { impersonationContext.Undo(); } 受保护 void Page_Load( object sender,EventArgs e) {} protected void btnUpload_Click( object sender,EventArgs e) { if (ImpersonateUser( username, , password)) { if (FileUpload1.PostedFile!= null ) { if (FileUpload1.HasFile) { string ext = System.IO.Path.GetExtension(FileUpload1.FileName); if (ext == 。xls || ext == 。rar || ext == 。XLS || ext == 。xlsx) { FileUpload1.SaveAs(Server.MapPath( 〜/ Admin / reports1 /)+ FileUpload1.FileName); // BindGrid(); } else { ClientScript.RegisterStartupScript( typeof (页面), SymbolError, < script type ='text / javascript'> javascript:alert('请选择正确的文件格式。');< / script>); return ; // lblerr2.Text =请选择正确的文件格式。; } } else { ClientScript.RegisterStartupScript( typeof (页面), SymbolError, < script type ='text / javascript'> javascript:alert('请选择要上传的文件。');< / script> ); return ; // Response.Write(请选择要上传的文件); } // string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); // string folderPath = @\\MyUNCShare \ MyFolder \ ; // string locationToSave = folderPath +\\ + fileName; // 尝试 // { // FileUpload1.PostedFile.SaveAs(locationToSave); // Response.Write(文件已上传。); // } // catch(exception ex) // { // Response.Write(Error:+ ex.Message ); // } } else { Response.Write( 请选择要上传的文件。); } UndoImpersonation(); } else { Response.Write( 失败); } } } 解决方案 如果你只需要上传一个文件有2个simeple方式,一个是用AJAX文件上传,这些让你上传多个文件,并有一些很好的java形式,看起来很好,在个人我不喜欢它,我更喜欢旧的阶梯,然后事情是如果你要同时上传一个文件或多个文件,我看你正在为xls,xlsx文件添加验证器 ,这让我想到你是否也需要将结果发送到数据库或只是存储文件的问题。 如果ts只是存储文件的问题。 单个文件。 < div id =Div1runat =server> < br /> < asp:fileupload id =FileUpload3runat =serverenabled =truexmlns:asp =#unknown/> < asp:button id =Button1runat =servertext =Uploadonclick =btnUpload_Clickxmlns:asp =#unknown/> < asp:label id =Label1runat =servertext =xmlns:asp =#unknown/> < br /> < asp:label id =Label6runat =servertext =xmlns:asp =#unknown/> < / div> protected void btnUpload_Click(object sender,EventArgs e) { if(FileUpload1.HasFile) { string FileName = Server.HtmlEncode(FileUpload1.FileName); string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower(); if(Extension!=。xls&& Extension!=。xlsx) { Response.Write(< script> alert('请选择一个Excel)要导入的电子表格!');< / script>); 返回; } string abc = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string strUploadFileName =〜/ TradeCompliance / Functional / Files_Archive /+ abc ++ DateTime.Now.ToString(yyyyMMddHHmmss)+ Extension; string FilePath = Server.MapPath(strUploadFileName); FileUpload1.SaveAs(FilePath); } } 如果需要同时存储多个文件,那么我使用它(检查在名称中你可以排序有效文件的类型来搜索上传和接受文件类型的应用程序适用于xls 97直到最后一个vertion): < br /> < input type =filemultiple =multiplerunat =serverwidth =300pxheight =300pxaria-dropeffect =movearia-multiline =true> aria-multiselectable =truedraggable =truename =pdfid =File1accept =application / pdf/>< asp:label id =Label1text =UploadComplete runat =servervisible =falsexmlns:asp =#unknown/>< br /> < asp:button id =Button2runat =servertext =UPLOADonclick =Button1_Clickxmlns:asp =#unknown/> < br /> < asp:label id =Label2runat =serverxmlns:asp =#unknown/> < br /> < hr /> < div> < asp:literal id =Literal1runat =serverxmlns:asp =#unknown/> < / div> < br /> < / input> protected void Button1_Click(object sender,EventArgs e) { string filepath = Server.MapPath(\\Logistics \\ArchiveFiles \\); string contentType =; string filename =; string HAWB_BOL =; string tempPath =; int filecnt = 0; HttpFileCollection uploadedFiles = Request.Files; Span1.Text = string.Empty; for(int i = 0; i< uploadedFiles.Count; i ++) { HttpPostedFile userPostedFile = uploadedFiles [i]; contentType = userPostedFile.ContentType; filename = Path.GetFileName(userPostedFile.FileName); HAWB_BOL = filename.Replace(。pdf,); filecnt = AD(HAWB_BOL); tempPath = filepath + filename; if(filecnt< 1) { try { if(userPostedFile.ContentLength> 0) { userPostedFile.SaveAs(tempPath); } } catch(Ex Ex) { Span1.Text + =错误:< br> + Ex.Message; } } else { userPostedFile.SaveAs(tempPath); File.Delete(tempPath); } } } < / br> 我只是删除了代码的圆顶部分,因为我在多个场景中保存到数据库中以获取文件可用的文件,但基本上只需要进行一些小的更改就可以实现其中任何一个。 在Web.Config文件中你必须添加这样的东西。 < system.web> < authentication mode =Windows/> < identity impersonate =trueusername =XUSERpassword =XPASSWORD/> < /system.web> < system.web> < authentication mode =Forms> < forms loginurl =〜/ Account / Logintimeout =2880defaulturl =〜//> < / authentication> < identity impersonate =trueusername =XUSERpassword =XPASSWORD/> < /system.web> 根据您的认证方法,这些应该有效。 i have to upload file without giving full permission to my folder where all files will be uploaded.I have to upload file using file impersonation in asp.netwhen i write identity impersonate="true" in web config it shows error to site.What I have tried:<identity impersonate="true" username="" password="" />public partial class Uploadfile : System.Web.UI.Page { public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll")] public static extern int LogonUserA(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool RevertToSelf(); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern bool CloseHandle(IntPtr handle); private bool ImpersonateUser(String userName, String domain, String password) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return true; } } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); return false; } private void UndoImpersonation() { impersonationContext.Undo(); } protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { if (ImpersonateUser("username", "", "password")) { if (FileUpload1.PostedFile != null) { if (FileUpload1.HasFile) { string ext = System.IO.Path.GetExtension(FileUpload1.FileName); if (ext == ".xls" || ext == ".rar" || ext == ".XLS" || ext == ".xlsx") { FileUpload1.SaveAs(Server.MapPath("~/Admin/reports1/") + FileUpload1.FileName); //BindGrid(); } else { ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'> javascript: alert('Please Select Proper file Format.');</script>"); return; //lblerr2.Text = "Please Select Proper file Format."; } } else { ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'> javascript: alert('Please select file to upload.');</script>"); return; //Response.Write("Please select file to upload"); } //string fileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName); //string folderPath = @"\\MyUNCShare\MyFolder\"; //string locationToSave = folderPath + "\\" + fileName; //try //{ // FileUpload1.PostedFile.SaveAs(locationToSave); // Response.Write("The file has been uploaded."); //} //catch (Exception ex) //{ // Response.Write("Error: " + ex.Message); //} } else { Response.Write("Please select a file to upload."); } UndoImpersonation(); } else { Response.Write("Failed"); } } } 解决方案 If you just need to upload a file there is 2 simeple ways, one is with the AJAX file upload, these let you upload multiple files and have some nice java forms that looks fine, in the personal I dont like it to much I prefere the old stile, then the thing is if you are going to upload a single file o multiple files at the same time, and Im looking you are adding validator for only xls, xlsx files, that make me think in if also you will need to thow the results in to a DB or is just matter to store the file.If ts just matter to store the file.Single File.<div id="Div1" runat="server"> <br /> <asp:fileupload id="FileUpload3" runat="server" enabled="true" xmlns:asp="#unknown" /> <asp:button id="Button1" runat="server" text="Upload" onclick="btnUpload_Click" xmlns:asp="#unknown" /> <asp:label id="Label1" runat="server" text="" xmlns:asp="#unknown" /> <br /> <asp:label id="Label6" runat="server" text="" xmlns:asp="#unknown" /></div>protected void btnUpload_Click(object sender, EventArgs e){ if (FileUpload1.HasFile) { string FileName = Server.HtmlEncode(FileUpload1.FileName); string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower(); if (Extension != ".xls" && Extension != ".xlsx") { Response.Write("<script>alert('Please select a Excel spreadsheet to import!');</script>"); return; } string abc = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string strUploadFileName = "~/TradeCompliance/Functional/Files_Archive/" + abc + " " + DateTime.Now.ToString("yyyyMMddHHmmss") + Extension; string FilePath = Server.MapPath(strUploadFileName); FileUpload1.SaveAs(FilePath); }}If multiple files needs to be stored at the same time then I use this (Check that in name you can sort the type of valid files to search for upload and the accept the type of file application works for xls 97 up to last vertion):<br /><input type="file" multiple="multiple" runat="server" width="300px" height="300px" aria-dropeffect="move" aria-multiline="true"> aria-multiselectable="true" draggable="true" name="pdf" id="File1" accept="application/pdf" /><asp:label id="Label1" text="UploadComplete" runat="server" visible="false" xmlns:asp="#unknown" /><br /><asp:button id="Button2" runat="server" text="UPLOAD" onclick="Button1_Click" xmlns:asp="#unknown" /><br /><asp:label id="Label2" runat="server" xmlns:asp="#unknown" /><br /><hr /><div> <asp:literal id="Literal1" runat="server" xmlns:asp="#unknown" /></div><br /></input> protected void Button1_Click(object sender, EventArgs e) { string filepath = Server.MapPath("\\Logistics\\ArchiveFiles\\"); string contentType = ""; string filename = ""; string HAWB_BOL = ""; string tempPath = ""; int filecnt = 0; HttpFileCollection uploadedFiles = Request.Files; Span1.Text = string.Empty; for (int i = 0; i < uploadedFiles.Count; i++) { HttpPostedFile userPostedFile = uploadedFiles[i]; contentType = userPostedFile.ContentType; filename = Path.GetFileName(userPostedFile.FileName); HAWB_BOL = filename.Replace(".pdf", ""); filecnt = AD(HAWB_BOL); tempPath = filepath + filename; if(filecnt < 1) { try { if (userPostedFile.ContentLength > 0) { userPostedFile.SaveAs(tempPath); } } catch (Exception Ex) { Span1.Text += "Error: <br>" + Ex.Message; } }else { userPostedFile.SaveAs(tempPath); File.Delete(tempPath); } } }</br>I just delete dome parts of the code as I save in the multiple scenario to a DB to get the files available against a file, but basically with some minor changes you should be able to implement any of these.At the Web.Config file you must add some thing like this.<system.web> <authentication mode="Windows" /> <identity impersonate="true" username="XUSER" password="XPASSWORD" /></system.web><system.web> <authentication mode="Forms"> <forms loginurl="~/Account/Login" timeout="2880" defaulturl="~/" /> </authentication> <identity impersonate="true" username="XUSER" password="XPASSWORD" /></system.web>Depending on your authentification method these should work. 这篇关于在ASP.NET中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 22:57
查看更多