How to upload image using ajax in asp.net mvc

Ram 21 Reputation points
2022-06-14T13:55:53.707+00:00

Hi guys how can i upload image using AJAX in ASP.NET MVC

Developer technologies ASP.NET ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-06-14T17:29:06.773+00:00

    you have two options

    1) pass a base64 string as part of a json payload.

    2) use the FormData object as the post content

    <form id="form">  
       <input type="file" id="file" name="file">  
       <button type="button">Upload</button>  
    </form>  
    
    <script>  
        if (!document.getElementById("file"))  
        {  
              alert("Select File first");  
              return;  
        }  
        var url = "/postfile";  
        var data = new FormData(document.getElementById("form"));  
        fetch(url, {  
            method: "POST",  
            data: data  
        });  
    </script>  
    

    .

    0 comments No comments

  2. Anonymous
    2022-06-17T05:36:14.623+00:00

    Hi @Ram ,

    how can i upload image using AJAX in ASP.NET MVC

    If your application is a .NET Framework application, such as .NET 4.7.2 API application, you could refer the following sample code:

    Index.html: 212329-index.txt

    212328-image.png

    Home controller: 212259-homecontroller.txt
    212317-image.png

    Then, the image will upload to the Uploads folder:

    212371-image.png

    If your application is an Asp.net core application, you can check the following code:

    Index.cshtml: 212287-core-index.txt
    212308-image.png

    Home controller: 212309-homecontroller.txt

    212276-image.png

    Then, the image was upload to the wwwroot\upload folder:

    212260-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.