How to Upload File in Spring Mvc
Introduction
I hope you all are fine. Today we will acquire how to perform upload and download operations in MVC. Please refer to the step-by-step approach in learning Model View Controller if you are new to MVC. Our MVC Master, Shivprasad koirala has explained the concepts in a perfect fashion.
Please run across this article in my blog here
This commodity has been selected as Article Of The Mean solar day for October 6th 2015 in Asp.net Customs
Please see this article in my weblog here
Download the source code
Background
Some days before, I got a requirement to develop a upload and download mechanism in my MVC awarding. Later completing it perfectly, I decided to share it with you all.
Using the code
Before moving further into the details, let u.s.a. showtime listing the key points we will explain in this commodity:
- Create a MVC awarding.
- Create a controller.
- Create View depending on the controller.
- Change the RouteConfig as needed.
- Create ActionResult for the actions.
- Create a folder where we need to save the downloaded files.
Let united states beginning with creating a controller chosen "myAction".
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Web;
- using Organisation.Web.Mvc;
- namespace UploadDownloadInMVC.Controllers
- {
- public grade myActionController : Controller
- {
- }
- }
As you can come across that the controller is empty; nosotros will be writing the action results adjacent.
- public ActionResult Index()
- {
- foreach ( string upload in Request.Files)
- {
- if (Asking.Files[upload].FileName != "" )
- {
- string path = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/" ;
- string filename = Path.GetFileName(Request.Files[upload].FileName);
- Request.Files[upload].SaveAs(Path.Combine(path, filename));
- }
- }
- return View( "Upload" );
- }
The activity issue shown above is for index. So, whenever the application loads, the activity result will be fired. For that, the following changes should be washed for RouteCofig.
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resources}.axd/{*pathInfo}" );
- routes.MapRoute(
- name:"Default" ,
- url:"{controller}/{activity}/{id}" ,
- defaults:new { controller = "myAction" , action = "Alphabetize" , id = UrlParameter.Optional }
- );
- }
- }
Every bit you tin can see in the Index Action, we are checking whether the asking parameter contains the files. If it exists, we volition save the selected file to the directory
/App_Data/uploads/ (that nosotros demand to manually create in our application). After returning to the view Upload, nosotros need to set up the Upload view.
Upload View
The following is the code for the Upload view.
- @{
- ViewBag.Title ="Upload" ;
- }
- <h2>Upload</h2>
- <script src="~/Scripts/jquery-i.11.1.min.js" ></script>
- <script>
- $(document).ready(function () {
- $('#btnUploadFile' ).on( 'click' , function () {
- var data = new FormData();
- var files = $( "#fileUpload" ).get(0).files;
- if (files.length > 0) {
- data.append("UploadedImage" , files[0]);
- }
- var ajaxRequest = $.ajax({
- type:"POST" ,
- url:"myAction/Alphabetize" ,
- contentType:false ,
- processData:fake ,
- data: data
- });
- ajaxRequest.done(role (xhr, textStatus) {
- });
- });
- });
- </script>
- <input blazon="file" name= "FileUpload1" id= "fileUpload" /><br />
- <input id="btnUploadFile" blazon= "push button" value= "Upload File" />
- @Html.ActionLink("Documents" , "Downloads" )
In the upload view, nosotros have the following:
- File uploader
- Upload button
- Ajax call to the controller ( myAction/Index)
Here, nosotros are adding the uploaded paradigm content to the grade data collection.
- var data = new FormData();
- var files = $( "#fileUpload" ).go(0).files;
- if (files.length > 0) {
- data.append("UploadedImage" , files[0]);
- }
Once the data is added to the course data drove, we will pass the data to the controller via ajax call. Sounds cool, right? If the process goes well, we will see the output as follows.
When you cull the file and click upload, your selected file will exist uploaded to the folder "uploads" equally nosotros have set information technology in the controller.
We have finished the process of uploading files. We will now motion to the downloading department. This is the right time to add the remaining actions to our controller. The following is the code.
- public ActionResult Downloads()
- {
- var dir = new Organization.IO.DirectoryInfo(Server.MapPath( "~/App_Data/uploads/" ));
- Organisation.IO.FileInfo[] fileNames = dir.GetFiles("*.*" ); List<string> items = new List<cord>();
- foreach (var file in fileNames)
- {
- items.Add(file.Name);
- }
- return View(items);
- }
- public FileResult Download(string ImageName)
- {
- var FileVirtualPath = "~/App_Data/uploads/" + ImageName;
- return File(FileVirtualPath, "application/force-download" , Path.GetFileName(FileVirtualPath));
- }
Exercise you call back that we have ready an action link in the "Upload" View?
- @Html.ActionLink( "Documents" , "Downloads" )
Adjacent, if we click on the "Documents" link, our Activity Upshot Downloads will be fired, correct? Now, the following code will explain what is happening hither.
- var dir = new Organization.IO.DirectoryInfo(Server.MapPath( "~/App_Data/uploads/" ));
- System.IO.FileInfo[] fileNames = dir.GetFiles("*.*" ); List<string> items = new List<string>();
- foreach (var file in fileNames)
- {
- items.Add(file.Name);
- }
- return View(items);
We are considering all the attached files, adding the file information to a list and returning this listing to the view "Download". Adjacent, here'south the need to set up another view. The following code is for the Download View.
Download View
- @{
- ViewBag.Championship ="Downloads" ;
- }
- <h2>Downloads</h2>
- @model List<cord>
- <h2>Downloads</h2>
- <table>
- <tr>
- <th>File Name</th>
- <thursday>Link</th>
- </tr>
- @for ( var i = 0; i <= Model.Count - 1; i++)
- {
- <tr>
- <td>@Model[i].ToString() </td>
- <td>@Html.ActionLink("Download" , "Download" , new { ImageName = @Model[i].ToString() }) </td>
- </tr>
- }
- </table>
Here, we are taking the data (that we are sending from the controller) about the uploaded files and creating the Html.ActionLinks dynamically.
Delight notation that we are calculation the Image name to the action. Hither is the output after performing the operations.
Equally in the preceding image, when you mouse over the link, information technology will testify the image name along with the controller URL. Click on the link to download the file. So simple, right?
Decision
I hope you lot liked the article. Please provide your valuable feedback; information technology matters a lot. Y'all can download the source code to determine more than.
Point of involvement
MVC, MVC Upload, MVC Download, File Uploading Using MVC, File Downloading Using MVC
Source: https://www.c-sharpcorner.com/UploadFile/65794e/uploading-and-downloading-in-mvc/
0 Response to "How to Upload File in Spring Mvc"
Post a Comment