1

I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks

I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks

  <td class="d-flex justify-content-around">

                <div>
                    <label asp-for="mostanadPath" class="btn btn-outline-info">
                        انتخاب تصویر
                        <span class="oi oi-file h5 text-dark"></span>

                    </label>
                    <span class="text-center mt-2" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>

                </div>
                <div>
                    <input type="button" onclick="UploadImage()" value="آپلود فایل" class="btn btn-outline-danger" id="btnUpLoad" />

                    <div id="divmessage" class="text-center hidden m-2"></div>

                    <input class="d-none" value="@ViewBag.proID" name="id" />
                </div>
                <input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
                <input id="mostanadPath" asp-for="mostanadPath" type="file" class="d-none">

                <div class="mt-5 col-6">
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped
                            active" role="progressbar"
                             aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>

                    </div>
                </div>


            </td>

<script>
    $("#mostanadPath").change(function () {
        var filename = this.files[0].name;
        $("#spnImageCartMlie").html(filename);
    });
</script>


<script>
    var UploadImage = function () {
        var data = new FormData;
        var file = $("#mostanadPath").get(0);
        var files = file.files;
        //کنترل سایز فایل
        if (files[0].size >= 5120000) {
            $("#spnImageCartMlie").removeClass('hidden');
            $("#spnImageCartMlie").text('حجم فایل بیش از 500 کیلوبایت است');
            $("#spnImageCartMlie").css("color", "red");
            return false;
        }


        for (var i = 0; i < files.length; i++) {
            data.append('filearray', files[i]);
            data.append('filesize', files[i].size);
        }
        data.append('path', "img\\mostandat\\");

        $.ajax({
            xhr: function () {
                var xhr = new window.XMLHttpRequest();

                xhr.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        percentComplete = parseInt(percentComplete * 100);

                        $('.progress-bar').width(percentComplete + '%');
                        $('.progress-bar').html(percentComplete + '%');

                    }
                }, false);

                return xhr;
            },
            url: '@Url.Action("UploadImageFile", "Project")',
            type: "POST",
            data: data,
            contentType: false,
            processData: false }).done(function (result) {
            if (result.status == "success") {

                toastr.success('فایل با موفقیت آپلود شد', {
                    timeOut: 2000,
                    closeButton: true,
                });


                $("#newCartMlieImagePathName").val(result.imagename);
            }

        }).fail(function (result) {
            if (result.status != "success") {
                toastr.warning('در حین آپلود مشکلی بوجود آمد', {
                    timeOut: 2000,
                    closeButton: true,
                });

            }
        });
    }
</script>

public IActionResult UploadImageFile(IEnumerable<IFormFile> filearray, String path)
{

    String fileName = _uploadFiles.UploadFilesFunc(filearray, path);

    return Json(new { status = "success", imagename = fileName });

}

1 Answer 1

2

You can use this JQuery code in your <script>:

$.ajax({
  xhr: function() {
  var xhr = new window.XMLHttpRequest();

  xhr.upload.addEventListener("progress", function(evt) {
    if (evt.lengthComputable) {
      var percentComplete = evt.loaded / evt.total;
      percentComplete = parseInt(percentComplete * 100);

      $('.progress-bar').width(percentComplete+'%');
      $('.progress-bar').html(percentComplete+'%');

     }
  }, false);

   return xhr;
  },
  url: yoururl,
  type: "POST",
  data: data,
  contentType: false,
  processData: false
  success: function(result) {
    console.log(result);
  }
});

and Add this code in your page

<div class="progress">
   <div class="progress-bar progress-bar-success progress-bar-striped 
    active" role="progressbar"
    aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>

then you can see the progress bar when you upload file. enter image description here

===============================================

If you want only one button,you can use this code:

<input type="file" id="files" />


<script>
$("#files").change(function () {
  $.ajax({

     //........

   });
})
</script>

enter image description here

=================================================

I just add the code I gave you above to ajax

<div class="container mt-4 col-2">
    
        <table class="table table-bordered">
     
            <tbody class="text-center">
                <tr>
                    <td>
                        <label asp-for="mostanadPath" class="btn btn-outline-info">
                            Image selection
                            <span class="oi oi-file h5 text-dark"></span>
    
                        </label>
                    </td>
    
                </tr >
                <tr>
                    <td>
                        <span class="text-center" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>
                        <input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
    
                    </td>
                </tr>
    
                <tr>
                    <td>
                        <input type="button" onclick="UploadImage()" value="Upload and display the image" class="btn btn-outline-danger" id="btnUpLoad" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <div id="divmessage" class="text-center hidden"></div>
                    </td>
                </tr>
            </tbody>                
        </table>
    
        <input asp-for="mostanadPath" type="file" class="d-none" >
    
    </div>

<div class="progress">
   <div class="progress-bar progress-bar-success progress-bar-striped 
    active" role="progressbar"
    aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>

@section Scripts {

    <script>
        $("#mostanadPath").change(function () {
            var filename = this.files[0].name;
            $("#spnImageCartMlie").html(filename);
        });
    </script>


    <script>
        var UploadImage = function () {
            var data = new FormData;
            var file = $("#mostanadPath").get(0);
            var files = file.files;
            //File size control
            if (files[0].size >= 512000) {
                $("#spnImageCartMlie").removeClass('hidden');
                $("#spnImageCartMlie").text('The file size is more than 500 KB');
                $("#spnImageCartMlie").css("color", "red");
                return false;
            }


            for (var i = 0; i < files.length; i++) {
                data.append('filearray', files[i]);
                data.append('filesize', files[i].size);
            }
            data.append('path', "img\\mostandat\\");

            $.ajax({
             //add here......
                xhr: function() {
                  var xhr = new window.XMLHttpRequest();

                  xhr.upload.addEventListener("progress", function(evt) {
                    if (evt.lengthComputable) {
                      var percentComplete = evt.loaded / evt.total;
                      percentComplete = parseInt(percentComplete * 100);

                      $('.progress-bar').width(percentComplete+'%');
                      $('.progress-bar').html(percentComplete+'%');

                     }
                  }, false);

                   return xhr;
                  },


                type: "post",
                  url: '/Home/UploadImageFile',
                data: data,
                contentType: false,
                processData: false
            }).done(function (result) {
                if (result.status == "success") {
                    $("#divmessage").text("Upload was successful.");
                    $("#divmessage").css("color", "green");
                    $("#divmessage").removeClass("hidden");


                    $("#newCartMlieImagePathName").val(result.imagename);
                }

            }).fail(function (result) {
                if (result.status != "success") {
                    $("#divmessage").css("color", "red");
                    $("#divmessage").removeClass("hidden");
                    $("#divmessage").text("There was a problem uploading.");
                }
            });


        }
    </script>
}

enter image description here

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you very much, your answer is correct. But can I have only one button to upload? It means only the file selection button and after selecting the file will be uploaded automatically and there is no need for a second button to upload
How can I do this? Please edit the code
Hi,I have edited my answer.
I applied your edit but it did not work. Please write a sample with my case
Please edit from my code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.