Contentful logo

Contentful Community

Creating an asset from a file isn't working with the JS SDK

I am trying to create an asset with the SDK but i seem to receive a 422 with no further error details.

Below is a snippet of the service i am using. I have looked through the documentation and looked at the file upload example on Github and cannot seem to figure out the issue.

Although, it appears that there are others who have asked similar questions so maybe it will be beneficial to create a revised example to display for users.

Now I am aware that 422 is ValidationFailed, UnknownField or InvalidEntry but as per the docs i pass in a HTML File so it should be valid.

file-upload-example: https://github.com/contentful-labs/file-upload-example

export class ContentfulService {

    constructor() { }

    private cdaClient = createClient({
        accessToken: environment.CONTENTFUL.accessToken
    });

    /**
     * createImage() creates a single asset from a HTML File and publishes it to Contenful.
     *
     * @param file HTML input File retrieved from a HTML input element of type file.
     */
    createImage(file: File) {
        return this.cdaClient.getSpace(environment.CONTENTFUL.space)
            .then(space => space.getEnvironment(environment.CONTENTFUL.environment))
            .then((env) => env.createAssetFromFiles({
                fields: {
                    title: {
                        'en-GB': file.name
                    },
                    file: {
                        'en-GB': {
                            contentType: file.type,
                            fileName: file.name,
                            file
                        }
                    }
                }
            }))
            .then((asset) => asset.processForAllLocales())
            .then((asset) => asset.publish())
            .catch(err => err);
    }
}

Thank you for your help

Nevermind, I got this working.

It was actually nothing to do with this part of the code, it was to do with how i was looping over this method, it wasn’t properly resolving before looping again for multiple uploads.

I’ll keep this in for reference though in case anyone else is having issues creating assets from files, the above should work for you