Family Tree JS has rich API, easily you can use it to upload avatars to your server
This is step by step tutorial on how to upload photos for Family Tree JS to your server in .NET core.
Step 1 - Installation
If you are already familiar with BALKAN FamilyTreeJS you can skip this step. There are two installation options: standalone or using npm
standalone installation
See our getting started page
npm installation
npm i @balkangraph/familytree.js
Step 2 - Client side implementation
BALKAN FamilyTreeJS has builtin edit form that you can use to edit the nodes data. The Edit Form has tons of configuration options you can learn more from this help article.
/// <reference path="FamilyTree.d.ts" />
var family = new FamilyTree('#tree', {
nodeBinding: {
img_0: 'photo'
},
editForm: {
generateElementsFromFields: false,
photoBinding: "photo",
elements: [
{ type: 'textbox', label: 'Photo Url', binding: 'photo', btn: 'Upload' },
]
}
});
Now lets load the nodes data or family members data, you can load from json, xml csv or even import the data from excel file, here we will use the load method
family.load([
{ id: 1, pids: [2], gender: 'female'},
{ id: 2, pids: [1], gender: 'male' },
{ id: 3, mid: 1, fid: 2, gender: 'female' },
]);
Now the family tree is ready and it will be displayed, but in many cases you will need uploaded images to your server. To send the upload image from the client to the server you can use "element-btn-click" event listener of the editUI interface and its setAvatar method
family.editUI.on('element-btn-click', function (sender, args) {
FamilyTree.fileUploadDialog(function (file) {
var data = new FormData();
data.append('files', file);
fetch('/Home/UploadPhoto', {
method: 'POST',
body: data
})
.then(response => {
response.json().then(responseData => {
args.input.value = responseData.url;
sender.setAvatar(responseData.url);
});
});
});
});
Step 3 - Server side implementation
On the server create standard http post action method in your .NET Core web app
[HttpPost]
public async Task<IActionResult> UploadPhoto(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
var file = files.First();
var path = Path.Combine(_host.WebRootPath, "photos", file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Json(new
{
url = new Uri(new Uri(Request.Scheme + "://" + Request.Host.Value), Url.Content("~/photos/" + file.FileName)).ToString()
});
}
The UploadPhoto action method will upload the portraits to a "photos" folder in wwwroot. If you are going to use the same location in production make sure that the IIS has write permissions to that folder.
See the code in GtiHub
Tell us if you have any questions in the comments below.