@section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
}
I added 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 >Icon Url</td>',
'<td >gelenveri</td>',
'<td>item.Sizes</td>',
'<td>item.CreatedDate</td>',
'<td > <button 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;
});
}
});
});
I am uploading with DropZone. I am using signalR to get progress value from backend while upload is happening but signalR is not working in front-end. how can i solve this problem. var connection = new signalR; it shows up as undefined. SignalR does not see its value at all. I can't send request to UploadHub because signalR is not working
CodePudding user response:
I used HTML
Dropzone
to build a simple example to test, but it works fine without the problem you said.
If you encounter a situation where the backend uploads normally but the frontend progress bar fails to load, it may be because you are developing locally, so your files will be uploaded in an instant. I suggest you use DevTools to limit your speed to 3G and that will somewhat simulate real world conditions.
Below is my test code:
Index.cshtml:
<div >
<div >
<!-- Uploader Dropzone -->
<div id="zdrop" >
<div id="upload-label" style="width: 200px;">
<i >cloud_upload</i>
<span >Drag your Files here</span>
<span>Some description here <span/>
</div>
</div>
<!-- Preview collection of uploaded documents -->
<div >
<div >
<span>Uploaded Files</span>
<i id="close" >close</i>
<i id="controller" >keyboard_arrow_down</i>
</div>
<div id="previews">
<div id="zdrop-template">
<div data-dz-thumbnail>
<div>
<span data-dz-name></span> <span data-dz-size></span>
</div>
<div >
<div style="width:0" data-dz-uploadprogress></div>
</div>
<div ><span data-dz-errormessage></span></div>
</div>
<div >
<a href="#!" data-dz-remove ><i >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>
Controller:
[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);
}
}