I want to upload a file from the client to the server. Is there a way to upload a file with SignalR or must i need a Controller for this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
SignalR is for real time messaging not uploading files.
Method 2
While SignalR cannot help with the actual upload, it can be used for updating the client with progress while a file is uploaded.
Method 3
This file uploading using file input bootstrap plugin (krajee)
You can also upload file without using this plugin.
@section Page{
<script src="~/Scripts/bootstrap-switch.min.js"></script>
<script src="~/Scripts/Uploader/fileinput.js"></script>
<link href="~/Scripts/Uploader/fileinput.css" rel="nofollow noreferrer noopener" rel="stylesheet" />
<script>
var itemHub = $.connection.ItemHub;
$(document).ready(function() {
$.connection.hub.start().done(function() {
//do any thing
});
$("#fileinput").fileinput({
allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
maxImageWidth: 700,
maxImageHeight: 700,
resizePreference: 'height',
maxFileCount: 1,
resizeImage: true
});
$("#fileinput").on('fileloaded', function (event, file, previewId, index, reader) {
var readers = new FileReader();
readers.onloadend = function () {
$(".file-preview-image").attr('src', readers.result);
}
readers.readAsDataURL(file);
});
$('#btnSave').click(function() {
var imagesJson = $('.file-preview-image').map(function () {
var $this = $(this);
return {
image: $this.attr('src'),
filename: $this.attr('data-filename')
};
}).toArray();
itemHub.server.getByteArray(imagesJson);
});
});
</script>
}
Hub class code
[HubName("ItemHub")]
public class ItemHub : Hub
{
public void GetByteArray(IEnumerable<ImageData> images)
{
foreach (var item in images ?? Enumerable.Empty<ImageData>())
{
var tokens = item.Image.Split(',');
if (tokens.Length > 1)
{
byte[] buffer = Convert.FromBase64String(tokens[1]);
}
}
}
}
public class ImageData
{
public string Description { get; set; }
public string Filename { get; set; }
public string Image { get; set; }
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0