Introduction
This is a very simple article to upload and view documents using MVC and Ajax. Sometimes a user needs to upload file(s) to the server and view. For example, if you want to upload photos, PDF documents, text files and so on. This article shall help you to upload and view documents in a browser at the same time. Here I have created an Area (right-click on ProjectName (projStudentInfo) > add > Area) > Enter Area Name (DocumentViewAndUpload).
Then right-click on controller of that area and add controller with the name DocViewUpload.
So here we have Areas -> DocumentViewAndUpload and controller DocViewUpload and View Index.cshtml.
Figure 1: Solution Explorer
Now in the controller we have an Index Action for which we have Index.cshtml in which we have a file upload control and a button.
Controller Code
- public ActionResult Index()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Index(HttpPostedFileBase file)
- {
- if (file != null && file.ContentLength > 0) try
- {
- string path = Path.Combine(Server.MapPath("~/Files"),
- Path.GetFileName(file.FileName));
- file.SaveAs(path);
- return Json(new {
- Error = false, Message = "File Uploaded Successfully..!!!", FilePath = file.FileName
- }, JsonRequestBehavior.AllowGet);
- }
- catch (Exception ex)
- {
- return Json(new {
- Error = false, Message = "File Not Uploaded"
- }, JsonRequestBehavior.AllowGet);
- }
- else
- {
- ViewBag.Message = "You have not specified a file.";
- }
- return View();
- }
- public FileResult ShowDocument(string FilePath)
- {
- return File(Server.MapPath("~/Files/") + FilePath, GetMimeType(FilePath));
- }
- private string GetMimeType(string fileName)
- {
- string mimeType = "application/unknown";
- string ext = System.IO.Path.GetExtension(fileName).ToLower();
- Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
- if (regKey != null && regKey.GetValue("Content Type") != null)
- mimeType = regKey.GetValue("Content Type").ToString();
- return mimeType;
- }
In the preceding code we have an Index action and Index action with a HttpPostedFileBase parameter. On the click of the button a parameterized Index will be called. The code will copy a file to the “File” folder and the JSON result is returned to view the jQuery. JSON returns the filename to jQuery that then calls ShowDocument with file name as parameter. We have the GetMimeType function that returns ContentType as a string.
Index.cshtml
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h2>Document View And Upload</h2>
- @using (Html.BeginForm("Index", "DocViewUpload", FormMethod.Post, new { @enctype = "multipart/form-data", @id = "MyForm" }))
- {
- <table border="0" cellpadding="0" cellspacing="0">
- <tr>
- <td>Please select File
- </td>
- <td>
- <input type="file" name="file" value="" id="myFile" />
- </td>
- <td></td>
- </tr>
- </table>
- }
-
- <button id="btnUpload">View Document</button>
- <div id="DOC1"></div>
- <script>
- $(document).ready(function () {
- $("#btnUpload").click(function () {
- if($("#myFile").val()=="")
- {
- alert("Please select a file");
- return false;
- }
- $('#MyForm').ajaxForm({
- complete: function (xhr) {
- var ret = $.parseJSON(xhr.responseText);
- if (ret.Error == false) {
- $("#DOC1").empty();
- $("#DOC1").html('
- <iframe src="@Url.Action("ShowDocument", "DocViewUpload", new { FilePath = "_FilePath" }) "'.replace("_FilePath", ret.FilePath) + ' style="width: 98%; height: 98%" ></iframe>');
- // $("#DOC1").show();
- $("#DOC1").dialog({
- autoOpen: true,
- modal: true,
- height:500,
- width:600,
- buttons: {
- OK: function () { $(this).dialog("close"); }
- },
- title: "Document",
- });
- }
- },
- error: function () {
- window.location.reload();
- }
- }).submit();
- });
- });
- </script>
NOTE: Add the following reference code to _Layout.cshtml (master page).
For the ajaxForm function we need form.js in the script folder.
- <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
- <script src="//code.jquery.com/jquery-1.10.2.js"></script>
- <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
- <script src="../../Scripts/form.js" type="text/javascript"></script>
Remove @Scripts.Render("~/bundles/jquery") if you see in _Layout.cshtml.
Figure 2: Choose File
Uploading Image file
Figure 3: File Uploading
Thank you very much for reading.