(Original) How to put the data into the folder that the Web cannot be accessed and downloaded to the user?

xiaoxiao2021-03-06  40

In the application, we may encounter such a situation, we need to temporarily generate a data file to download it, but every time you download must be judged, that is, the user does not get this downloaded URL to continue downloading the file, below is implementation method . The file is saved as a CSV format, which is convenient for data import. The basic principle is to use the stream to send the file and send the stream to the client with the Response.WriteFile. The table structure with text: http: //blog.9cbs.net/lovecherry/archive/2005/02/25/301441.aspxSqlConnection conn = new SqlConnection (System.Configuration.ConfigurationSettings.AppSettings [ "conn"]); SqlDataAdapter DA = New SqldataAdapter ("Select * from TB1", CONN); DataSet DS = New Dataset (); DA.FILL (DS, "Table1"); DataTable DT = DS.TABLES ["Table1"]; string name = SYSTEM .Configuration.ConfigurationSettings.AppSettings [ "downloadurl"]. ToString () DateTime.Today.ToString ( "yyyyMMdd") new Random (DateTime.Now.Millisecond) .Next (10000) .ToString () ". csv" ; // Store the path specified in Web.config, the file format is the current date 4 bit random filestream fs = new filestream (name, filemode.create, fileaccess.write); streamwriter sw = new streamwriter (fs, system) .Text.Encoding.Getencoding ("GB2312")); SW.WRITELINE ("Auto Number, Name, Age"); Foreach (Datarow Dr In Dt.Rows) {SW.WRITELINE (DR ["i"] ", " DR [" VNAME "] ", " DR [" IAGE "]);} sw.close (); response.addhead (" Content-Disposition "," Attachment; FileName = " Server.urlencode (Name )); Response.contentType = "Applicati ON / MS-EXCEL "; // Specify that the return is a stream that cannot be read by the client, must be downloaded response.writefile (name); // sends the file stream to the client response.end (); here In front of the section code you can place some judgments, it is determined whether this user can download the file, the generated file can be stored in the database, and you can download it directly without repeating the file.

转载请注明原文地址:https://www.9cbs.com/read-53732.html

New Post(0)