Let begin now.
Step 1: Create a View(uploadDocument.cshtml) in MVC and add below HTML table and add input type of type file.
- <table>
- <tr>
- <td>
- Upload Document
- <span style="color: Red;">*</span>:
-
- </td>
- <td style="width: 15%;">
- <input type="file" id="file" name="file" />
- </td>
- </tr>
- <tr>
- <td colspan="2" style="text-align: center;">
- <input type="button" class="btn btn-primary" name="Submit" id="Submit" value="Upload" />
-
-
- <input type="button" class="btn btn-primary" name="Reset" id="Cancel" value="Reset" />
- </td>
- </tr>
- </table>
Step 2: Add controller to MODEL name it as UploadConteroller.CS and then apply the logic to save uploaded fle.
- [HttpPost]
- public JsonResult UploadDocument(HttpPostedFileBase File) {
- try {
-
- var files = Request.Files[0];
- if (files != null && files.ContentLength > 0) {
- var path = Server.MapPath("~/Content/UploadedFiles/" + File.FileName);
- File.SaveAs(path);
- }
- return Json(“Uploaded the file”, JsonRequestBehavior.AllowGet);
- } catch (Exception ex) {
- return Json(ex.Message, JsonRequestBehavior.AllowGet);
- }
- }
Step 3: Now its time to work with JQuery.
- var data = new FormData();
- var files = $("#file").get(0).files;
- if (files.length > 0) {
- data.append("file", files[0]);
- }
-
- $.ajax({
- type: "POST",
- dataType: "json",
- url: '@Url.Action("UploadDocument", "Upload")',
- contentType: false,
- processData: false,
- data: data,
- success: function(result) {
- alert(result);
-
- },
- error: function(xhr, ajaxOptions, thrownError) {
- alert(result);
-
- }
- });
I hope this would help developers & beginners. So start using and enjoy coding.