Uploading files via angularJs in Backoffice

I’m trying to upload files via angularJs in the backoffice, and have already tried the UmbracoAuthorizedApiController, UmbracoApiController, and even the SurfaceController (to make sure I’m not going crazy).

The C# Controller has this method:

[HttpPost, DisableRequestSizeLimit]
public async Task<ActionResult> UploadFile([FromForm] IFormFile data)
{
    if (data == null)
        return BadRequest();

    try
    {
        await _extensions.UploadFileAsync(data);
        return Ok();
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error Uploading file");
        return BadRequest();
    }
}

and the angular controller is performing this

async function uploadFiles() {
    vm.loading = true;
    let files = document.getElementById('file_upload').files;
    if (files.length == 0) {
        notificationsService.warning('Please first choose or drop any file(s)...');
        vm.loading = false;
        return;
    }
    for (let i = 0; i < files.length; i++) {
        let formData = new FormData();
        formData.append('file', files[i]);
        resources.postFile(formData)
            .then(success => {
            if (success) {
                vm.filesUploaded ??= [];
                notificationsService.success(`file ${files[i].name} uploaded successfully`);
                vm.filesUploaded.push(files[i].name);
            }

        }, failure => {
            notificationsService.error(`Could not upload: ${failure.data.Title}`)
            console.log(failure);
        });
    }
    vm.loading = false;
}

and the angularJs resource file has this post

function postFile(formData) {
    return $http({
        method: 'POST',
        url: `${baseApiUrl}UploadFile`,
        data: formData
    })
}

And yet, it keeps submitting null files. I attempted several different tutorials online, but nothing works. I’m sure it’s something trivial, maybe someone can see it and point me in the right direction, please?



This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/110844-uploading-files-via-angularjs-in-backoffice

To update this conversation. I’ve found that uploading multiple files at once is very problematic in angularjs and I could not make it work. Using vanilla JavaScript `fetch` works better.

uploadImages: function (files) {

    if (!files || files.length === 0) return;
    const formData = new FormData();

    // append each file
    for (let i = 0; i < files.length; i++) {
        formData.append('files[]', files[i]); // or 'files' if backend expects that
    }

    return fetch(`${dashboardBaseUrl}ImportQuotesFromImages`, {
        method: 'POST',
        body: formData      // browser sets multipart/form-data + boundary
    })
}
[HttpPost, DisableRequestSizeLimit]
public async Task<IActionResult> ImportTextFromImages()
{
    var texts = new List<ImportEntry>();
    var files = Request.Form.Files;
    try
    {
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                var text = await file.OcrAsync();
                if (text is not null)
                    texts.Add(quote);
            }
        }

        return Ok(new { Message = $"{files.Count} images processed.", Texts = texts });
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error Uploading file from extension");
        return BadRequest();
    }

}
1 Like