DeliveryUpload UploadFile (Streaming)

Description

Upload a catalog file to the 2BA database.
Please refer to our Webservices documentation how to use this upload function regarding access and security.

Resource URL

json: https://api.2ba.nl/1/streaming/DeliveryUpload/UploadFile

The input is a MultipartFormDataContent with the parameter:
 file

required

 Stream with file. This file should be one of the accepted formats (bestandsformaten) compressed using zip, 7z or gzip. The maximum filesize is 2GB. For larger files see our alternative upload through SFTP

Response Object

The UploadFile service returns the normale HTTP Status as response.

c# sample code

       public async Task Upload(byte[] file, string filename)
        {
            string result;
            if (string.IsNullOrEmpty(_refreshToken))
            {
                // Only once during the application life time the GetTokenResourceOwnerPasswordCredentials is called
                await GetTokens();
            }
            if (_client == null) {
                // The HttpClient object is intended to live for as long as this application needs to make HTTP requests.
                InitializeClient();
            }

            var uri = new Uri(_baseUri, "Streaming/DeliveryUpload/UploadFile");

            using (var content = new MultipartFormDataContent())
            {
                // Add parameter process. Process file after upload?
                content.Add(new StringContent(((int)_settings.ProcessFile).ToString()), "process");
                
                // Add file as stream
                content.Add(new StreamContent(new MemoryStream(file)), filename, filename);

                try
                {
                    result = await PostFile(uri, content);

                    if (string.IsNullOrEmpty(result))
                    {
                        // Tokens refreshed. Retry once!
                        result = await PostFile(uri, content);
                        if (string.IsNullOrEmpty(result))
                        {
                            throw new FileWatchUploadException($"Retry upload failed. Stop retrying.");              
                        }
                    }
                }
                catch (TaskCanceledException ex)
                {
                    // Check ex.CancellationToken.IsCancellationRequested here.
                    // If false, it's pretty safe to assume it was a timeout.
                    if (ex.CancellationToken.IsCancellationRequested)
                    {
                        _logger.LogError($"Problem uploading file *** Timeout ***");
                    }
                    throw;
                }
                catch (Exception e)
                {
                    throw new FileWatchUploadException($"Problem uploading file to { _settings.RestServiceUrl }", e);
                }
            }

            return JsonConvert.DeserializeObject(result);
        }

        private void InitializeClient()
        {
            _client = new HttpClient();
            _client.MaxResponseContentBufferSize = 256000;
            _client.Timeout = TimeSpan.FromMinutes(30);
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
        }

        private async Task PostFile(Uri uri, MultipartFormDataContent content)
        {
            var result = string.Empty;

            using (var response = await _client.PostAsync(uri, content))
            {
                if (response.IsSuccessStatusCode)
                {
                    // return result
                    _logger.LogInformation("Upload OK: " + _baseUri);
                    result = await response.Content.ReadAsStringAsync();
                    return result;
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    // return empty result
                    _logger.LogInformation($"Unauthorized at: { _baseUri }. Start refreshing tokens");
                    var tokens = await _authorizeServices.RefreshToken(_refreshToken);
                    _client.DefaultRequestHeaders.Remove("Bearer");
                    _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens.access_token);
                    return result;
                }
                else
                {
                    // throw exception
                    throw new FileWatchUploadException($"Error uploading file. Statuscode: {response.StatusCode }. {response.ReasonPhrase} \n {uri}");
                }
            }
        }

        private async Task GetTokens()
        {
            try
            {
                var tokenResponse = await _authorizeServices.GetTokenResourceOwnerPasswordCredentials();
                _refreshToken = tokenResponse.refresh_token;
                _accessToken = tokenResponse.access_token;
            }
            catch (Exception)
            {
                _logger.LogError($"Unable to get tokens at { _settings.AuthServiceUrl }");
                throw;
            }
        }
    }
</string></importfilelist></importfilelist>
This site is registered on wpml.org as a development site.