Skip to main content

Upload attachments

In this guide, you will learn how to upload file attachments to Fatture in Cloud using the API; this is a tricky operation, so you'll need to fill out the request properly to make it work. We'll use the Taxes API (F24) as an example, but the process is similar for other endpoints that support file uploads.

Retrieve your Company ID!

In this example, we'll suppose you have to manage just one Company, so we simply inserted its ID directly in the code. If, instead, you need to be able to manage multiple companies, you'll need to retrieve the ID of the current company in some way.

Check the Company-scoped Methods page for more info.

👣  File Upload Process​

In order to attach a file to a Fatture in Cloud document, you need to follow this two-step procedure:

  • Upload the file and retrieve the attachment token;
  • Use the attachment token to link the uploaded file to the desired entity (like an invoice or receipt) in the Create or Update request of your document type.

In the Taxes API (F24) use case, this process can be translated into the following steps:

🍬 Supported Endpoints​

Currently, the available Upload Attachment endpoints are the following:

The following examples will focus on the Upload F24 Attachment endpoint, but the process is similar for the other endpoints.

⚙ Code Examples​

In this paragraph, we'll provide vanilla code examples showing how to upload attachments using different programming languages.

SDKs make it easier!

Please note that the SDKs will make this process much easier to implement, as they already handle multipart/form-data requests internally. You can find SDK code examples in the Invoice Creation guide or in the SDKs Readme files (check the GitHub repositories).

C# SDK issue

It seems that C# SDK's Readme is providing a broken code example based on MemoryStream, resulting in the "Extension not valid" error. We suggest you check the Invoice Creation guide provided above for a working example.

You can also refer to the following GitHub pages for more info:

The attachment upload process requires sending a POST request with multipart/form-data encoding, including the file content and the filename as separate fields. Your REST clients could also provide built-in support for multipart requests, so please check their documentation for more details.

Here are examples showing how to upload attachments using different programming languages:

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace FattureInCloud.Taxes
{
public class AttachmentData
{
[JsonProperty("attachment_token")]
public string AttachmentToken { get; set; }
}

public class UploadF24AttachmentResponse
{
[JsonProperty("data")]
public AttachmentData Data { get; set; }
}

public class TaxesAttachmentClient
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl;
private readonly string _accessToken;

public TaxesAttachmentClient(string accessToken, string baseUrl = "https://api-v2.fattureincloud.it")
{
_accessToken = accessToken ?? throw new ArgumentNullException(nameof(accessToken));
_baseUrl = baseUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_accessToken}");
}

public async Task<UploadF24AttachmentResponse> UploadTaxesAttachmentAsync(
int companyId,
string filePath,
string filename = null)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));

if (!File.Exists(filePath))
throw new FileNotFoundException($"File not found: {filePath}");

try
{
// If filename is not specified, use the file name
if (string.IsNullOrEmpty(filename))
filename = Path.GetFileName(filePath);

// Create multipart/form-data content
using var form = new MultipartFormDataContent();

// Add the file
var fileStream = File.OpenRead(filePath);
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "attachment", filename);

// Add filename as a separate field
form.Add(new StringContent(filename), "filename");

// Endpoint URL
string url = $"{_baseUrl}/c/{companyId}/taxes/attachment";

// Make the POST request
var response = await _httpClient.PostAsync(url, form);

// Verify that the response is successful
response.EnsureSuccessStatusCode();

// Read and deserialize the response
string jsonResponse = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<UploadF24AttachmentResponse>(jsonResponse);

Console.WriteLine("Upload completed successfully!");
Console.WriteLine($"Attachment token: {result.Data?.AttachmentToken}");

return result;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP error during upload: {ex.Message}");
throw;
}
catch (Exception ex)
{
Console.WriteLine($"Error during upload: {ex.Message}");
throw;
}
}

public void Dispose()
{
_httpClient?.Dispose();
}
}

class Program
{
static async Task Main(string[] args)
{
const int companyId = 12345; // Replace with your company ID
const string filePath = "./invoice.pdf"; // Path to the file to upload
const string filename = "invoice.pdf";
const string accessToken = "YOUR_ACCESS_TOKEN"; // Replace with your token

var client = new TaxesAttachmentClient(accessToken);

try
{
var result = await client.UploadTaxesAttachmentAsync(companyId, filePath, filename);
Console.WriteLine($"Result: {JsonConvert.SerializeObject(result, Formatting.Indented)}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
client.Dispose();
}
}
}
}

📎  Attach the file to the document​

When the upload is successful, you'll receive a response containing the attachment token:

{
"data": {
"attachment_token": "ATTACHMENT_TOKEN"
}
}

Once you have the attachment_token, you can attach the file to your document (invoice, receipt, etc.) by including it in the appropriate API request when creating or updating the document.

For example, when using the Create F24 API method, you would include the attachment_token value in the request body, in the $.data.attachment_token field as follows:

{
"data": {
"amount": 840.36,
"description": "PAGAMENTO IVA 2021",
"due_date": "2021-12-31",
"status": "paid",
"payment_account": {
"id": 111
},
"attachment_token": "ATTACHMENT_TOKEN"
}
}

The file will then be associated with the document in Fatture in Cloud.

📚  Additional resources​