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".

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  System.IO;
  4. using  System.Linq;
  5. using  System.Web;
  6. using  Organisation.Web.Mvc;
  7. namespace  UploadDownloadInMVC.Controllers
  8. {
  9. public grade  myActionController : Controller
  10.     {
  11.     }
  12. }

As you can come across that the controller is empty; nosotros will be writing the action results adjacent.

  1. public  ActionResult Index()
  2. {
  3. foreach  ( string  upload in  Request.Files)
  4.     {
  5. if  (Asking.Files[upload].FileName != "" )
  6.         {
  7. string  path = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/uploads/" ;
  8. string  filename = Path.GetFileName(Request.Files[upload].FileName);
  9.             Request.Files[upload].SaveAs(Path.Combine(path, filename));
  10.         }
  11.     }
  12. return  View( "Upload" );
  13. }

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.

  1. public class  RouteConfig
  2. {
  3. public static void  RegisterRoutes(RouteCollection routes)
  4.     {
  5.         routes.IgnoreRoute("{resources}.axd/{*pathInfo}" );
  6.         routes.MapRoute(
  7.             name:"Default" ,
  8.             url:"{controller}/{activity}/{id}" ,
  9.             defaults:new  { controller = "myAction" , action = "Alphabetize" , id = UrlParameter.Optional }
  10.         );
  11.     }
  12. }

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.

  1. @{
  2.     ViewBag.Title ="Upload" ;
  3. }
  4. <h2>Upload</h2>
  5. <script src="~/Scripts/jquery-i.11.1.min.js" ></script>
  6. <script>
  7.     $(document).ready(function  () {
  8.         $('#btnUploadFile' ).on( 'click' , function  () {
  9. var  data = new  FormData();
  10. var  files = $( "#fileUpload" ).get(0).files;
  11. if  (files.length > 0) {
  12.                 data.append("UploadedImage" , files[0]);
  13.             }
  14. var  ajaxRequest = $.ajax({
  15.                 type:"POST" ,
  16.                 url:"myAction/Alphabetize" ,
  17.                 contentType:false ,
  18.                 processData:fake ,
  19.                 data: data
  20.             });
  21.             ajaxRequest.done(role  (xhr, textStatus) {
  22.             });
  23.         });
  24.     });
  25. </script>
  26. <input blazon="file"  name= "FileUpload1"  id= "fileUpload"  /><br />
  27. <input id="btnUploadFile"  blazon= "push button"  value= "Upload File"  />
  28. @Html.ActionLink("Documents" , "Downloads" )

In the upload view, nosotros have the following:

  1. File uploader
  2. Upload button
  3. Ajax call to the controller ( myAction/Index)

Here, nosotros are adding the uploaded paradigm content to the grade data collection.

  1. var  data = new  FormData();
  2. var  files = $( "#fileUpload" ).go(0).files;
  3. if  (files.length > 0) {
  4.     data.append("UploadedImage" , files[0]);
  5. }

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.

  1. public  ActionResult Downloads()
  2. {
  3. var  dir = new  Organization.IO.DirectoryInfo(Server.MapPath( "~/App_Data/uploads/" ));
  4.     Organisation.IO.FileInfo[] fileNames = dir.GetFiles("*.*" ); List<string> items = new  List<cord>();
  5.     foreach (var  file in  fileNames)
  6.     {
  7.         items.Add(file.Name);
  8.     }
  9. return  View(items);
  10. }
  11. public  FileResult Download(string ImageName)
  12. {
  13. var  FileVirtualPath = "~/App_Data/uploads/"  + ImageName;
  14. return  File(FileVirtualPath, "application/force-download" , Path.GetFileName(FileVirtualPath));
  15. }

Exercise you call back that we have ready an action link in the "Upload" View?

  1. @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.

  1. var  dir = new  Organization.IO.DirectoryInfo(Server.MapPath( "~/App_Data/uploads/" ));
  2. System.IO.FileInfo[] fileNames = dir.GetFiles("*.*" ); List<string> items = new  List<string>();
  3. foreach (var  file in  fileNames)
  4. {
  5.     items.Add(file.Name);
  6. }
  7. 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

  1. @{
  2.     ViewBag.Championship ="Downloads" ;
  3. }
  4. <h2>Downloads</h2>
  5. @model List<cord>
  6. <h2>Downloads</h2>
  7. <table>
  8.     <tr>
  9.         <th>File Name</th>
  10.         <thursday>Link</th>
  11.     </tr>
  12.     @for  ( var  i = 0; i <= Model.Count - 1; i++)
  13.     {
  14.         <tr>
  15.             <td>@Model[i].ToString() </td>
  16.             <td>@Html.ActionLink("Download" , "Download" , new  { ImageName = @Model[i].ToString() }) </td>
  17.         </tr>
  18.     }
  19. </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

nevilleaple1962.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel