Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
26 Feb
2021

How to upload Image file using AJAX and jquery

by Shubham Batra

2146

Ajax 

So starting of from the beginning Ajax is used for Asynchronous Javascript and XML. We can use it for many purposes. Few basic uses of Ajax are:-

  • Update page without reloading the page providing better performance.
  • Request data from a server - after the page has loaded which can be used in loading Partial Views.
  • Send data to a server without reload - in the background making it easier to performance Save, Delete operations smoothly.

Ajax in Asp.Net MVC

Ajax can be used anywhere where we can use jquery. So you have seen various ways of using Ajax in our previous article  Using Ajax in Asp.Net MVC. But posting fileupload files becomes a little complicated with Ajax.So we will learn How to upload Image file using AJAX and jquery. So let's start from beginning:-

Step-1

So you have to add a fileupload filed on your view and now we will make some changes in Ajax to post that file on controller. We have also kept the three textboxes for some dummy data.

So for posting files and other data we have to send data by adding to formdata.

FormData is introduced to allow developers to build forms objects dynamically (and can even include files from the user's file system), and then to send this form object via AJAX.

So we will create a new formdata object and than add all the required values in that formdata using formdata.append. You will also add the file here . Remember to use the same keys which you have used on controller to receive tha data.

One thing to remember here is you have to use contenttype false which was json in previous methods we have seen in last article.And also set processdata to false

    $(function () {
        $("#btnGet6").click(function () {
            var formData = new FormData();
            var empIds = $("#txtId").val();
            var empNames = $("#txtName").val();
            var empSalarys = $("#txtSalary").val();
            var totalFiles = document.getElementById("FileUpload").files.length;
            debugger;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById("FileUpload").files[i];
                formData.append("fileUpload", file);
                formData.append("empId", empIds);
                formData.append("empName", empNames);
                formData.append("empSalary", empSalarys);
            }
            $.ajax({
                type: 'post',
                url: '/Home/AjaxMethodFileUpload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    debugger;
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + " Your Salary Is: " + response.EmpSalary + " And Your File Name Is: " + response.File);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

On the controller side we have to using same way like we have used earlier for first three parameters. Like giving same name which we have added in formdata. And then we will use a parameter of type of HttpPostedFileBase to receive the file.You will get you file in this parameter. Also you can get the file in Request.Files. So this is how you can get your file posted in mvc.

 
        [HttpPost]
        public JsonResult AjaxMethodFileUpload(string empId, string empName, string empSalary, HttpPostedFileBase fileUpload)
        {
            PersonModel personModel = new PersonModel
            {
                EmpId = empId,
                EmpName = empName,
                EmpSalary = empSalary,
                File = fileUpload.FileName
            };
            return Json(personModel);
        }

  • |
  • How to upload Image file using AJAX andjQuery , upload Image file using AJAX and jquery , Ajax call , file upload using ajax , file uploading using ajax and jquery

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
C#
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier