How do I resolve Uncaught ReferenceError: signalR is not defined

How do I resolve Uncaught ReferenceError: signalR is not defined

 @section scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
    }

我添加了 signalR CDN

    jQuery(function ($) {
    //burada Dropzone eklentisinin otomatik ayarları almasını engelliyoruz.
   // Dropzone.autoDiscover = false;
    //ben tıklayarak yükleme fonksiyonunu istemediğim için burada "clickable" yani tıklanabilirliği false yapıyorum
    Dropzone.clickable = false;
    Dropzone.autoDiscover = false;
    var uploader = $(document.body).dropzone({
        url: '/Upload/Upload',

        clickable: false,
        chunking: true,
        parallelChunkUploads: true,
        chunkSize: 1048576,
        uploadMultiple: false,
        addRemoveLinks: true,
        maxFilesize: 100,
        thumbnailWidth: 80,
        thumbnailHeight: 80,
        parallelUploads: 1,
        retryChunks: true,
        autoProcessQueue: true,
        autoQueue: true,
        headers: {
            'serviceUrl': getToLocalStorage("serviceUrl"), 'token': getToLocalStorage("token")
        },
        previewTemplate: document.querySelector('.itemProgressListContainer').innerHTML,
        previewsContainer: ".itemProgressListContainer ",

        accept: function (file, done) {

           // if (file.size > 102048576) {
           //     Swal.fire({
           //         icon: 'error',
           //         title: 'Oops...',
           //         text: 'Hata Oluştu! Dosya Fazla Büyük',
           //         footer: '<a href>Why do I have this issue?</a>'
           //   });
           //   return;
           //}
            return done();
            //uzantı kontrol boyut kontrolu yap
        },
        success: function () {

            Dropzone.autoDiscover = false;

            /*
             tr etiketine data-id attribute eklemiyor.
            var tablom = $('#example').DataTable();
            var rowNode = tablom.row.add([
                // COMMENT - need function here to add row id as <tr id="999"> //
                '<td class="editableColumns">Icon Url</td>',
                '<td class="editableColumns">gelenveri</td>',
                '<td>item.Sizes</td>',
                '<td>item.CreatedDate</td>',
                '<td class="center hidden-xs"> <button class="btn context-menu-one btn btn-neutral fffid" data-ffid="item.Id"><b>...</b></button><input type="hidden" value="item.Id" name="Id" /></td>'
            ]).draw(false).id = 'nextid';
            */
        },
        error: function () {
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Hata Oluştu! Dosya Fazla Büyük',
                footer: '<a href>Why do I have this issue?</a>'
            });
        },
        init: function () {
            var self = this;
            // config
            self.options.addRemoveLinks = true;
            self.options.dictRemoveFile = "Delete";
            //New file added
            self.on("addedfile", function (file) {
                $('#template').css('visibility', 'visible');
                console.log('new file added ', file);
            });
            // Send file starts
            self.on("sending", function (file, xhr, formData) {
                var folderId = $('.selectedItem').attr("data-folderid");
                var dType = $('.selectedItem').attr("data-dType");
                var relativePath = $('.selectedItem').attr("data-relativePath");
                var directoryPath = $('.selectedItem').attr("data-directoryPath");
                var size = $('.selectedItem').attr("data-size");
                var fileName = $('.selectedItem').attr("data-fileName");
                var itemId = generateUUID();
                console.log('upload started', file);
                formData.append("folderId", folderId);
                formData.append("dType", dType);
                formData.append("relativePath", relativePath);
                formData.append("directoryPath", directoryPath);
                formData.append("size", size);
                formData.append("fileName", fileName);
                formData.append("itemId", itemId);


                $('.progress-bar').width('0');
                $('.progress-bar').show();
            });
            // File upload Progress
            self.on("totaluploadprogress", function (progress) {
                
                var conssssnection = window.signalR;
                var connection = new signalR.HubConnectionBuilder()
                    .withUrl('/UploadHub')
                    .configureLogging(signalR.LogLevel.Information)
                    .build();
                this.connection.start().catch(function (err) {
                    return console.error(err.toString());
                });
                connection.on('sendProgress', function (progress) {
                    $('.progress-bar').width(progress + '%');
                })

              
               
            });
            self.on("queuecomplete", function (progress) {
                $('.progress-bar').delay(999).slideUp();
                $('.progress-bar').remove();
                self.removeFile(file);
                Dropzone.autoDiscover = false;
            });
            self.on('success', function (file, result) {
                Dropzone.autoDiscover = false;
            });
        }
    });
});

我正在使用 DropZone 上传。我正在使用 signalR 在上传时从后端获取进度值,但 signalR 在前端不起作用。我怎么解决这个问题。 var connection = new signalR;它显示为未定义。 SignalR 根本看不到它的价值。 我无法向 UploadHub 发送请求,因为 signalR 不工作

我用HTML+Dropzone搭建了一个简单的例子来测试,但是没有你说的问题,效果很好。

如果遇到后台上传正常但前端进度条加载失败的情况,可能是因为你是本地开发,所以你的文件会瞬间上传。我建议您使用 DevTools 将速度限制为 3G,这将在一定程度上模拟真实世界的情况。

下面是我的测试代码:

Index.cshtml:

<div class="row">
        <div class="col s12">
            <!-- Uploader Dropzone -->
            <div id="zdrop" class="fileuploader ">
                <div id="upload-label" style="width: 200px;">
                    <i class="material-icons">cloud_upload</i>
                    <span class="title">Drag your Files here</span>
                    <span>Some description here <span/>
                </div>
            </div>
            <!-- Preview collection of uploaded documents -->
            <div class="preview-container">
                <div class="header">
                    <span>Uploaded Files</span> 
                    <i id="close" class="material-icons">close</i>
                    <i id="controller" class="material-icons">keyboard_arrow_down</i>
                </div>
                <div class="collection card" id="previews">
                    <div class="collection-item clearhack valign-wrapper item-template" id="zdrop-template">
                        <div class="left pv zdrop-info" data-dz-thumbnail>
                            <div>
                                <span data-dz-name></span> <span data-dz-size></span>
                            </div>
                            <div class="progress" >
                                <div class="determinate" style="width:0" data-dz-uploadprogress></div>
                            </div>
                            <div class="dz-error-message"><span data-dz-errormessage></span></div>
                        </div>

                        <div class="secondary-content actions">
                            <a href="#!" data-dz-remove class="btn-floating ph red white-text waves-effect waves-light"><i class="material-icons white-text">clear</i></i></a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>

<script>
    $(document).ready(function(){

                initFileUploader("#zdrop");

                function initFileUploader(target) {
                    var previewNode = document.querySelector("#zdrop-template");
                    previewNode.id = "";
                    var previewTemplate = previewNode.parentNode.innerHTML;
                    previewNode.parentNode.removeChild(previewNode);


                    var self = new Dropzone(target, {
                        url: '/Home/UploadFile',
                        maxFilesize:20,
                        previewTemplate: previewTemplate,
                        autoQueue: true,
                        previewsContainer: "#previews",
                        clickable: "#upload-label"
                    });

                    self.on("addedfile", function(file) { 
                        $('.preview-container').css('visibility', 'visible');
                    });

                    self.on("totaluploadprogress", function (progress) {

                        var conssssnection = window.signalR;
                        var connection = new signalR.HubConnectionBuilder()
                            .withUrl('/UploadHub')
                            .configureLogging(signalR.LogLevel.Information)
                            .build();
                        //this.connection.start().catch(function (err) {
                        //    return console.error(err.toString());
                        //});
                        connection.on('sendProgress', function (progress) {
                            $('.progress .determinate').width(progress + '%');
                        })
                        //var progr = document.querySelector(".progress .determinate");
                        //if (progr === undefined || progr === null)
                        //  return;

                        //progr.style.width = progress + "%";
                    });

                    self.on('dragenter', function () {
                        $('.fileuploader').addClass("active");
                    });

                    self.on('dragleave', function () {
                        $('.fileuploader').removeClass("active");           
                    });

                    self.on('drop', function () {
                        $('.fileuploader').removeClass("active");   
                    });
                }
            });
</script>

控制器:

[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
      var uploads = Path.Combine(_environment.WebRootPath, "uploads");
      if (file.Length > 0)
      {
          using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
          {
              await file.CopyToAsync(fileStream);
          }
      }
      return View();
}

Startup.cs:

app.UseEndpoints(endpoints =>
{
      endpoints.MapHub<UploadHub>("/UploadHub");
}

UploadHub.cs:

public class UploadHub : Hub
{
        public async Task sendProgress(int progress)
        {
            await Clients.All.SendAsync("ReceiveMessage", progress);
        }
}

测试结果: