There are two ways to upload a file in the Media API. One is to use the extension method, which is a quick way to do it. The other way is to do it manually by using three different services:
- BlobService: to store the file's binary data.
- FileMetadataExtractorService: to extract all Exchangeable image file format (Exif) information from the file and save that along with the file.
- FileService: to save the file object to the database.
Regardless of what way we use, the files need to be put under a folder that has to be created first :
var folder = new Folder(_folderFieldTemplate.SystemId, Guid.NewGuid().ToString());
_folderService.Create(folder);
The extension method
There is an extension method for the FileService, located under Litium.Media namespace. It receives the folder's system id, file name and file stream.
File file;
using (fileInputStream)
{
file = _fileService.Create(_folder.SystemId, fileName, fileInputStream);
}
Note that the fileInputStream object is the input stream, where there can be a file from the HTTP request or from your local machine.
The manual way
1. Store the blob
var blob = _blobService.Create(File.BlobAuthority);
using (var stream = blob.GetDefault().OpenWrite())
{
await file.CopyToAsync(stream);
}
Note that the file object is the input stream, where there can be a file from the HTTP request or from your local machine.
2. Extract the Exif data
The following code extracts the Exif data and puts it to the file object. Note that Exif data is available only for images and movies.
var template = _fieldTemplateService.FindFileTemplate(fileExtension);
var fileObject = new File(template.SystemId, folder.SystemId, blob.Uri, "File name")
_fileMetadataExtractorService.UpdateMetadata(template, fileObject, null, blob.Uri);
3. Save the file to the database
Last but not least, we need to save the file to the database
_fileService.Create(fileObject);