Several ways to download ASP. NET MVC file (welcome discussion) There are several ways to download files in ASP. Prerequisite: The file to be downloaded must be in the server directory, but not in the Web Project Server directory Download I don't know, but I kinda want to know. The first type: The simplest hyperlink method,<a> the href of the label directly to the destination file address, so that the address is easily exposed to cause hotlinking, this is not said The second type: Background download In the background download can be subdivided into several download methods First, at the front desk, we need a <a> tag
<a href="~/home/download"get file</a>
Home is the action for Controller,download. If you need to pass some parameters, you can:
<a href="~/home/download?id=1"get file</a>
In the background: (1) Return to FileStream
Public filestreamresult Download () { string"aaa.txt"; The file name saved by the client string filePath = Server.MapPath ("~/document/123.txt "); // Path return File (new"text/plain", fileName);}
Where: "Text/plain" is the file MIME type (2) Return file
Public fileresult Download () { string filePath = Server.MapPath ("~/document/123.txt"); // Path return " Text/plain " " Welcome.txt " ); Welcome.txt is the name saved by the client }
(3) TransmitFile method
1 Publicvoid Download ()2 {3 stringFileName ="Aaa.txt";//file name saved by the client4 stringFilePath = Server.MapPath ("~/document/123.txt");//Path5FileInfo FileInfo =NewFileInfo (filePath);6Response.Clear ();//clears all content output from the buffer stream7Response.clearcontent ();//clears all content output from the buffer stream8Response.ClearHeaders ();//clears all headers in the buffer stream9Response.Buffer =true;//This value indicates whether the output is buffered and sent after the entire response has been processedTenResponse.AddHeader ("content-disposition","attachment;filename="+fileName); OneResponse.AddHeader ("Content-length", FileInfo. Length.tostring ()); AResponse.AddHeader ("content-transfer-encoding","binary"); -Response.ContentType ="Application/unknow";//Gets or sets the HTTP MIME type of the output stream -response.contentencoding = System.Text.Encoding.GetEncoding ("gb2312");//Gets or sets the HTTP character set of the output stream the Response.TransmitFile (filePath); - Response.End (); -} (4) Response sub-block download
1 Public voidDownload ()2 {3 stringFileName ="Aaa.txt";//file name saved by the client4 stringFilePath = Server.MapPath ("~/document/123.txt");//Path5 6System.IO.FileInfo FileInfo =NewSystem.IO.FileInfo (filePath);7 if(Fileinfo.exists = =true)8 {9 Const LongChunkSize =102400;//100K Read the file every time, only read 100K, this can alleviate the pressure of the serverTen byte[] buffer =New byte[ChunkSize]; One A response.clear (); -System.IO.FileStream IStream =System.IO.File.OpenRead (filePath); - LongDatalengthtoread = Istream.length;//get the total size of the downloaded file theResponse.ContentType ="Application/octet-stream"; -Response.AddHeader ("content-disposition","attachment; Filename="+Httputility.urlencode (FileName)); - while(Datalengthtoread >0&&response.isclientconnected) - { + intLengthread = istream.read (buffer,0, Convert.ToInt32 (ChunkSize));//the size of the read -Response.OutputStream.Write (Buffer,0, lengthread); + Response.Flush (); ADatalengthtoread = Datalengthtoread-Lengthread; at } - response.close (); - } -} <input>+ajax method To focus on this method, Ajax can not return the file stream, so that the use of Ajax call any of the above-mentioned methods are problematic, can not download files. Therefore, you can only let the background return the URL address of the desired download file, and then call Windows.location.href. Pros: Ajax can pass several parameters (of course, in JSON form), 100 is irrelevant. What if you use <a href= "url? Parameter = value "method of ></a> pass 100 to write dead ... (company needs, at least more than 100 parameters to pass) Cons: Support download Exe,rar,msi and other types of files. For TXT will be opened directly, use with caution! For other infrequently used type files, the error is directly. So my advice is to get multiple parameters, find all the files that need to be downloaded through the database, then compress the package, and then return to the URL to download. (If you are one to the user, the user is crazy) ! So the question comes again, C # How to use code implementation of some local files compressed into the server directory? I don't know about that. Because you simply put in the directory folder is not used, we usually add a file in a server directory is right, add the XXX item so that you can really put the file in the server. But how to implement the pure code?? * Possible solution: First in the project directory, an empty RAR file or a little Exe,msi file, and then in the background after the packaging of some files to replace it, do not know if it is feasible. (1) First empty the contents of the original compressed package (2) Compress the file into a compressed package (3) Return to Xxx.rar Front:
<input type="button" id="downloadbutton"/>
Ajax:
$("#downloadbutton"). Click (function () {$.ajax ({type:"GET", URL:"/home/download", data: {ID:"1"}, DataType:"JSON", success:function (result) {Window.location.target="_blank"; Window.location.href=result; } }) }) Background:
Public string Download (int ID) { string'document/123.msi "; // Path return filePath; }
Here, the ID is not what the role of the background will not use what server. MapPath, it must be wrong. Write the Server project folder/file name directly. PostScript: If there are other good methods please make sure to leave a message, updated. Because of this problem a lot of people are online to ask, I also tried a lot of methods. Hope to help others to help themselves. |