net生成下载文件|c#net上传和下载文件代码

⑴ 如何在ASP.NET中下载文件

但是这样的下载有几个问题:1. 无法下载不存在的文件:例如,我们若是想把程序动态(临时)产生的文字,当作一个文件下载的时候(也就是该文件其实原先并不是真的存在,而是动态产生的),就无法下载。2. 无法下载存储于数据库中的文件:这是类似的问题,该文件并没有真的存在,只是被存放在数据库中的某个位置(某笔记录中的某个栏位)的时候,就无法下载。3. 无法下载不存在于Web文件夹中的文件:文件确实存在,但该文件夹并不是可以分享出来的Web文件夹,例如,该文件的位置在C:/winnt,您总不会想要把该文件夹当作Web文件夹吧?这时候,由于您无法使用Redirect指向该位置,所以无法下载。4. 下载文件后,原本的页面将会消失。1. 这个文件可能是通过ASP.NET程序动态产生的,而不是确实存在于Server端的文件;2. 或是它虽然存在于伺服器端的某个实体位置,但我们并不想暴露这个位置(如果这个位置公开,很可能没有权限的用户也可以在网址栏上输入URL直接取得!!!)3. 或是这个位置并不在网站虚拟路径所在的文件夹中。(例如C:/Windows/System32…)这时候,我们就得采用不同的方式:Shared Function DownloadFile(ByVal WebForm As System.Web.UI.Page, ByVal FileNameWhenUserDownload As String, ByVal FileBody As String)WebForm.Response.ClearHeaders()WebForm.Response.Clear()WebForm.Response.Expires = 0WebForm.Response.Buffer = TrueWebForm.Response.AddHeader(Accept-Language, zh-tw)'文件名称WebForm.Response.AddHeader(content-disposition, attachment; filename= & Chr(34) & System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) & Chr(34))WebForm.Response.ContentType = Application/octet-stream'文件内容WebForm.Response.Write(FileBody)WebForm.Response.End()End Function上面这段代码是下载一个动态产生的文本文件,若这个文件已经存在于服务器端的实体路径,则可以通过下面的函数:Shared Sub DownloadFile(ByVal WebForm As System.Web.UI.Page, ByVal FileNameWhenUserDownload As String, ByVal FilePath As String)WebForm.Response.ClearHeaders()WebForm.Response.Clear()WebForm.Response.Expires = 0WebForm.Response.Buffer = TrueWebForm.Response.AddHeader(Accept-Language, zh-tw)'文件名称WebForm.Response.AddHeader(content-disposition, attachment; filename= & Chr(34) & System.Web.HttpUtility.UrlEncode(FileNameWhenUserDownload, System.Text.Encoding.UTF8) & Chr(34))

⑵ asp.net网页中,怎样实现用户上传文件,自动在网页中生成超链接,并可以点击超链接用户可以该下载文件

protectedstringUpLoad(System.Web.UI.WebControls.FileUploadUP_FILE)//参数是一个上传控件{stringphotourl=string.Empty;//上传文件if(UP_FILE.PostedFile.ContentLength>0){//设定上传文件的保存路径stringstrName=UP_FILE.PostedFile.FileName;FileInfofl=newFileInfo(strName);//Response.Write(fl.CreationTime.ToString());string[]strs=strName.Split('\');stringstrSaveDir="file/"+strs[strs.Length-1];//取得文件名(抱括路径)里最后一个"."的索引intintExt=strName.LastIndexOf(".");//取得文件扩展名stringstrExt=strName.Substring(intExt);strExt=strExt.ToLower();//if(strExt!=".jpeg"&&strExt!=".jpg"&&strExt!=".gif")//{//Response.Write("<scriptlanguage=javascript>alert('文件类型必须为.gif、.jpg、.jpeg')</script>");//return;//}//if(UP_FILE.PostedFile.ContentLength>3000000)//{//Response.Write("<scriptlanguage=javascript>alert('图片大小超过了限制')</script>");//return;//}UP_FILE.PostedFile.SaveAs(Server.MapPath(strSaveDir));return"上传成功!";}else{return"请选择要上传的文件!";}}

⑶ 各位大哥问个问题:asp.net 如何在服务器生成word文件 并提供下载

***DataTable、GridView、DataList导出至Word或Excel而对Repeater不行!因为DataGrid和DataList都是继承自WebControl类,而Repeater则是继承自Control类***使用时,先引入名称空间:using Insus.NET。此Dll的类别名称为:ExportToFile***这代码要加上去!不然会出现错误! public override void VerifyRenderingInServerForm(Control control) { }成功CODE:using System.Data.SqlClient;using Insus.NET;//引入空间public partial class firstdaytwo : System.Web.UI.Page{ ExportToFile ojfile = new ExportToFile();//实例化一定要 public override void VerifyRenderingInServerForm(Control control)//这个方法要加上不然出错 { } protected void Page_Load(object sender, EventArgs e) { bindData(); } public void bindData() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Container"].ConnectionString); con.Open(); SqlDataAdapter da = new SqlDataAdapter("select * from Sgird", con); DataSet ds = new DataSet(); da.Fill(ds); this.GridView1.DataSource = ds; this.GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { ojfile.ToWord(GridView1, "ssss");//ssss是你要取的文件名!可以用个textbox让它动态的改名,ojfile是上面的实例 }}你要下一个DLL引入:ExportToFile.dll 实例就上面都说明的

⑷ asp.net 如何实现将服务器上的文件下载到本地

给你提供一点代码:

string fileURL = this.Server.MapPath("你要下载的文件路径");//文件路径,可用相对路径

FileInfo fileInfo = new FileInfo(fileURL);

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=" +

Server.UrlEncode(fileInfo.Name.ToString()));//文件名

Response.AddHeader("content-length", fileInfo.Length.ToString());//文件大小

Response.ContentType = "application/octet-stream";

Response.ContentEncoding = System.Text.Encoding.Default;

Response.WriteFile(fileURL);

⑸ c#.net上传和下载文件代码

public static void FileDownload(string FileName) { String FullFileName = System.Web.HttpContext.Current.Server.MapPath(FileName); FileInfo DownloadFile = new FileInfo(FullFileName); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.ClearHeaders(); System.Web.HttpContext.Current.Response.Buffer = false; System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8)); System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString()); System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } 下载,直接调用方法try { if (FileUpload1.PostedFile.FileName.Length == 0) { Response.Write("<script>alert(\"上传路径不能为空!\");</script>"); return; } string filename = this.FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.LastIndexOf("\\") + 1); string houzhui = FileUpload1.PostedFile.FileName.Substring(this.FileUpload1.PostedFile.FileName.LastIndexOf(".") + 1); if (houzhui == "gif" || houzhui == "jpg" || houzhui == "bmp") { FileUpload1.PostedFile.SaveAs(Server.MapPath("image/" + filename)); Response.Write("<script>alert(\"上传文件成功!\");</script>"); } else { Response.Write("<script>alert(\"上传文件必须是gif,jpg,bmp格式!\");</script>"); return; } } catch (Exception ex) { Response.Write("<script>alert(\"" + ex.Message + "\");</script>"); }上传,根据自己需要稍加改动

⑹ .net如何实现文件下载功能

你在绑定的时候直接绑定一个超链接.它的href等于该文件的路径就OK了.如:<ahref='文件的路径/<%#DataBinder.Eval(Container.DataItem,"文件的列名")%>'><%#DataBinder.Eval(Container.DataItem,"文件的列名")%></a>———————怎么个意思?实现文件下载?超链接直接链接到该文件.就是下载了.至于提示存放路径.重命名.等操作.是不需要你去写的.

⑺ .NET处理文件提供下载,并发用户过50出现服务器超时情况。 跪求大神出谋解决方案啊!!

下载的文件能否在下载之前就生成出来,如果可以,则采用这个方案,不行的话,需要看看的生成文件的代码能否有优化的地方,如果是复杂的任务导致的,则建议将复杂任务从WEB分离出去,即WEB只是负责和用户交互,不负责处理,具体处理则交给其他程序,你描述不是太清楚,也就只能这样给你意见了,我这边的需求和你差不多,但是一般高峰时期200左右用户同时上传文件也没有出现拒绝服务的情况(我这边需求:用户多选上传文件,一个文件需要在服务器上生成PDF和SWF的两个版本,同时在数据库中至少要写入2条记录,如果是修改的情况,还会更新数据库)

⑻ 关于.net中文件的下载(C#)

string filepath="文本.txt";Rsponse.Write("<script>window.open('"+filepath+"')</script>");filepath里的路径可以是绝对路径:http://www..com/…/…/文本.txt相对路径:files/文件.exe根目录相对路径:/WEB/files/文件.rar明白了吧?

⑼ 如何在asp.net中如何实现文件的下载功能。

protectedvoidBtnDownload_Click(objectsender,EventArgse){SqlConnectionconn=newSqlConnection(ConfigurationManager.ConnectionStrings["sql"].ToString());conn.Open();stringstrSql="selecttop1timagefromtest";SqlCommandcmd=newSqlCommand(strSql,conn);SqlDataReaderdr=cmd.ExecuteReader(CommandBehavior.CloseConnection);if(dr.Read()){byte[]by=(byte[])dr[0];Response.AddHeader("Content-Disposition","attachment;filename=ceshi.txt");//设置读取的文件头Response.AddHeader("Content-Length",by.Length.ToString());Response.ContentType="text/plain";//设置输出类型这里可以保存在数据库中动态实现类型Response.OutputStream.Write(by,0,by.Length);//输出Response.Flush();}conn.Close();}

另外也可以把二进制流还原成文件,然后直接提供路径用超链接下载,或者用Response.WriteFile(文件路径)来实现下载。

⑽ ASP.NET 数据导出到excel文件给客户端下载的几种方法麻烦告诉我

实现方法:SqlConnectionconn=newSqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);SqlDataAdapterda=newSqlDataAdapter("select*fromtb1",conn);DataSetds=newDataSet();da.Fill(ds,"table1");DataTabledt=ds.Tables["table1"];stringname=System.Configuration.ConfigurationSettings.AppSettings["downloarl"].ToString()DateTime.Today.ToString("yyyyMMdd")newRandom(DateTime.Now.Millisecond).Next(10000).ToString()".csv";//存放到web.config中downloarl指定的路径,文件格式为当前日期4位随机数FileStreamfs=newFileStream(name,FileMode.Create,FileAccess.Write);StreamWritersw=newStreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));sw.WriteLine("自动编号,姓名,年龄");foreach(DataRowdrindt.Rows){sw.WriteLine(dr["ID"]","dr["vName"]","dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename="Server.UrlEncode(name));Response.ContentType="application/ms-excel";//指定返回的是一个不能被客户端读取的流,必须被下载Response.WriteFile(name);//把文件流发送到客户端Response.End();方法二:导出到csv文件,不存放到服务器,直接给浏览器输出文件流优点:1、随时生成,不需要占用资源2、可以结合身份认证3、同样利于数据交换实现方法:SqlConnectionconn=newSqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);SqlDataAdapterda=newSqlDataAdapter("select*fromtb1",conn);DataSetds=newDataSet();da.Fill(ds,"table1");DataTabledt=ds.Tables["table1"];StringWritersw=newStringWriter();sw.WriteLine("自动编号,姓名,年龄");foreach(DataRowdrindt.Rows){sw.WriteLine(dr["ID"]","dr["vName"]","dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename=test.csv");Response.ContentType="application/ms-excel";Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");Response.Write(sw);Response.End();对方法一,二补充一点,如果你希望导出的是xls文件分隔符用\t就可以了,不要用逗号代码修改如下:sw.WriteLine("自动编号\t姓名\t年龄");foreach(DataRowdrindt.Rows){sw.WriteLine(dr["ID"]"\t"dr["vName"]"\t"dr["iAge"]);}另外,修改输出的文件扩展名为xls即可。方法三:从datagrid导出html代码,生成excel文件,给客户端下载优点:1、有固定的格式,样子好看(datagrid的样子)局限性:1、不适合数据交换,里面有html代码,比较乱,没有固定格式2、datagrid不能有分页、排序等,否则出错实现方法:Response.Clear();Response.Buffer=false;Response.Charset="GB2312";Response.AppendHeader("Content-Disposition","attachment;filename=test.xls");Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");Response.ContentType="application/ms-excel";this.EnableViewState=false;System.IO.StringWriteroStringWriter=newSystem.IO.StringWriter();System.Web.UI.HtmlTextWriteroHtmlTextWriter=newSystem.Web.UI.HtmlTextWriter(oStringWriter);this.DataGrid1.RenderControl(oHtmlTextWriter);Response.Write(oStringWriter.ToString());Response.End();在这里说明一点:有的网友反映代码出现“没有dr["id"]”之类的错误,这个代码是按照我的数据结构来写的,到时候相关的字段要换成你自己的才是。


赞 (0)