C# mvc download stream
Now the only thing left to do is to take the buffered data and send it on its way to the client as a text file. The following snippet shows how this is done. Flush ; mstream. This lets the browser know how much data is being transfered Response. AddHeader "Content-Length", byteArray. As you can see this solution is pretty straight forward. Through the use of a memorystream and header manipulation you are able to dynamically retrieve data from a database and send it to the browser as a file.
One thing to note is that this example applies this methodology using an ASP. NET page. Though this will work, you will notice that once the text file has been downloaded the page ASP. NET still remains in the browser. This is caused by the fact that server has already sent its response back to the browser in the form of the text file.
There are a couple of different ways to get around this orphaned page. One is to implement this methodology using an http handler, rather than an ASP. Below is the screenshot of the Solution Explorer window where you can see the Folder Directory i. Files and it containing three files. Following is a Model class named FileModel with one property i. You will need to import the following namespace.
The Controller consists of two Action methods. Action method for handling File Display operation. Later, the values of the Array are copied to a Generic List collection consisting objects of FileModel class and then returned to the View. Action method for handling File Download operation.
This action method handles the File Download operation and when the ActionLink is clicked, the name of the File to be downloaded is sent to this method. And then the Byte Array object is sent for download using the File function. GetFiles Server. ReadAllBytes path ;. Inside the View, the FileModel class is declared as List which specifies that it will be available as a Collection. Displaying the Files.
Downloading the File. DirectoryInfo Server. Add file. Now, the following code will explain what is happening here. Next, here's the need to set another view. The following code is for the Download View.
ActionLinks dynamically. Please note that we are adding the Image name to the action. Here is the output after performing the operations. As in the preceding image, when you mouse over the link, it will show the image name along with the controller URL. Click on the link to download the file. So simple, right? I hope you liked the article. Please provide your valuable feedback; it matters a lot. You can download the source code to determine more.
View All. Sibeesh Venu Updated date Jan 25, I hope you all are fine. Please see this article in my blog here. Some days earlier, I got a requirement to develop a upload and download mechanism in my MVC application. Before moving further into the details, let us first list the key points we will explain in this article:.
0コメント