This post was most recently updated on July 17th, 2024
When we upload a file in contentful, then it must be linked with an asset, other wise the uploaded file cannot be viewed or linked to an entry. Below are the steps mentioned that must be followed serially:
1) Upload the file in contentful from Blob Storage
public async Task
{
string uploadid = string.Empty;
try
{
byte[] dataFiles;
BlobContainerClient container = new BlobContainerClient(“
BlobClient blob = container.GetBlobClient(filename);
Stream blobStream = blob.OpenReadAsync().Result;
using (var target = new MemoryStream())
{
blobStream.CopyTo(target);
dataFiles = target.ToArray();
}
var uploadReference = await _helper.GetClient().UploadFile(dataFiles);
if (uploadReference != null)
{
uploadid = uploadReference.SystemProperties.Id;
}
return uploadid;
}
catch (Exception ex)
{
_logger.LogError(“Error in uploading file in contentful” + ex.Message);
throw ex;
}
}
2) Create asset in contentful with reference to the upload id
public async Task
{
try
{
SystemProperties system = new SystemProperties();
system.Type = “Link”;
system.LinkType = “Upload”;
system.Id = uploadID;
UploadReference uploadReference = new UploadReference();
uploadReference.SystemProperties = system;
var managementAsset = new ManagementAsset();
managementAsset.SystemProperties = new SystemProperties();
managementAsset.Title = new Dictionary
{ “
};
managementAsset.Files = new Dictionary
{
{“
{
ContentType=”images/jpg”,
FileName=filename,
UploadReference= uploadReference
}
}
};
var assetDetails = await _helper.GetClient().CreateAsset(managementAsset, “
return assetDetails.SystemProperties.Id;
}
catch (Exception ex)
{
_logger.LogError(“Error in creating asset in contentful” + ex.Message);
throw ex;
}
}
3) Process Asset
public async Task
{
try
{
var managementAsset = new ManagementAsset();
managementAsset.SystemProperties = new SystemProperties();
await _helper.GetClient().ProcessAsset(id,
return true;
}
catch (Exception ex)
{
_logger.LogError(“Error in processing asset” + ex.Message);
throw ex;
}
}
4) Publish Asset
public async Task
{
try
{
var assetdetails = _helper.GetClient().GetAsset(assetID).Result;
var asset = await _helper.GetClient().PublishAsset(assetID, assetdetails.SystemProperties.Version.Value);
return true;
}
catch (Exception ex)
{
_logger.LogError(“Error in publishing asset” + ex.Message);
throw ex;
}
}
If we need to fetch any asset details e.g. asseturl we need to call the following method,-
public async Task
{
string asseturl = string.Empty;
try
{
var asset = await _helper.GetClient().GetAsset(assetid);
asseturl = asset.Files.ToList()[0].Value.Url;
return asseturl;
}
catch (Exception ex)
{
throw ex;
}
}