File Upload - Documentation

This documentation describes how to upload files.
The target field must be configured as field type 70.

This documentation describes these endpoints:

  • api/{endpoint}/FileUpload/{id}
  • api/{endpoint}/FileUpload/Key/{key}

C#

Create an instance of System.Net.Http.HttpClient:

// A reference to System.Net.Http.dll is required
// Required namespaces for this example
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

private const string BaseUrl = "http://localhost/E3k.Web/";
private const string Username = "TestUser";
private const string Password = "123456789";

private HttpClient GetClient()
{
    var client = new HttpClient
    {
        BaseAddress = new Uri(BaseUrl)
    };

    // Set authorization header
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", GetAuthorizationHeader());

    return client;
}

private string GetAuthorizationHeader()
{
    var combination = $"{Username}:{Password}";

    // Create a base64 string form username and password combination
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(combination));
}

Adding file as multipart form and sending post request:

private const string FileUploadKeyUrl = "api/Address/FileUpload/Key/{0}";

private const string TestFile1 = "TestFile1.txt";
private const string TestFile2 = "TestFile2.txt";

/// <summary>
/// Upload multiple files to web api
/// </summary>
/// <param name="addressNumber">Address number</param>
public async Task UploadFiles(string addressNumber)
{
    var client = GetClient();

    using (var content = new MultipartFormDataContent())
    {
        // Adding the files as stream content
        content.Add(PrepareStreamContent(TestFile1, "F071", "text/plain"));
        content.Add(PrepareStreamContent(TestFile2, "F150", "text/plain"));

        // Sending post request to upload the files
        var response = await client.PostAsync(String.Format(FileUploadKeyUrl, addressNumber), content);

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine("Upload failed.");
            return;
        }

        // Reading the response from web api
        var responseString = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"Response: {responseString}");
    }
}

/// <summary>
/// Prepares the stream content with content disposition headers for the file upload
/// </summary>
/// <param name="fileName">Name of file</param>
/// <param name="field">Target file number in europa3000</param>
/// <param name="contentType">Content type of file</param>
/// <returns>Stream content</returns>
private StreamContent PrepareStreamContent(string fileName, string field, string contentType)
{
    var streamContent = new StreamContent(GetFile(fileName));

    // Name and FileName are required for the web api to know in which field the data should be saved.
    streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
    {
        Name = $"\"{field}\"",
        FileName = $"\"{fileName}\""
    };
    streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

    return streamContent;
}

/// <summary>
/// Get file content as memory stream
/// </summary>
/// <param name="fileName">Name of file</param>
/// <returns>File content as memory stream</returns>
private MemoryStream GetFile(string fileName)
{
    var stream = new MemoryStream();
    var filePath = GetFilePath(fileName);

    using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        fileStream.CopyTo(stream);

    // Reset stream position
    stream.Position = 0L;

    return stream;
}

private string GetFilePath(string fileName)
{
    return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
}

If the request was valid and the data could be saved to europa3000 database, web API responds with following JSON:

{
    "F071": true,
    "F150": true
}

It's a dictionary indicating if the file was successfully saved to the target field (true).
A false value would mean the data could not be written to the database.

In case of a bad request a collection of file upload validations are returned, describing the error.
A description can be found here: FileUploadValidation

JavaScript

const BaseUrl = "http://localhost/E3k.Web/";
const Username = "TestUser";
const Password = "123456789";
const filePath = "TestFile1.txt";
const reportNumber = "000001"; 

function upload() {
    var formData = new FormData();
    var fileRequest = new XMLHttpRequest();
    
    fileRequest.responseType = "blob";
    fileRequest.open("GET", filePath, true);
    
    fileRequest.onreadystatechange = function () {
        if (fileRequest.readyState === 4) {
            if (fileRequest.status === 200 || fileRequest.status == 0) {
                formData.append("F071", fileRequest.response, getFileName(filePath));
                
                fetch(BaseUrl + "api/Address/FileUpload/Key/" + reportNumber, {
                    method: "post",
                    headers: getHeaders(),
                    body: formData
                })
                .then(function (response) {
                    return response.status === 200;
                })
                .catch((error) => {
                    console.error('Error:', error);
                    return false;
                });
            }
        }
    };
    fileRequest.send(null);
} 

/*
* This method returns the headers
* needed for the web API request
*/
function getHeaders() {
    return new Headers({
        "Authorization": "Basic " + getBase64Combination()
    });
}

/*
* This method returns the Basic Auth header
* for the web API request in base64
*/
function getBase64Combination() {
    var combination = Username + ":" + Password;
    return btoa(combination);
} 

/*
* This method return the filename from a path
* e.g. "c:/temp/temp.txt" => "temp.txt"
*/
function getFileName(fullPath) {
    return fullPath.split('\\').pop().split('/').pop();
}