4

I'm attempting to POST images to Drupal 8 via the REST api. The creation is successful (201) and the images appear in the files list. However, there are problems. I'm not sure if they are independent of one another of is they are related.

1.The images are created with a temporary status. Would prefer "permanent".

2.The MIME type is set to "application/octet-stream" and the images don't render. I've discovered that by chaning the "uri" in the json object I'm posting to be an explicit uri like "public://photograph.jpg", the MIME type gets set to image/* and this work.

This is the code i'm using:

<script>
    function getCsrfToken(callback) {              //get token
        jQuery
            .get('http://vhscms/cms/rest/session/token')
            .done(function(data) {
                var csrfToken = data;
                callback(csrfToken);
            });
    }

    function postImage(csrfToken, image) {         //post image
        console.log(image);
        jQuery.ajax({
            url: 'http://vhscms/cms/entity/file?_format=hal_json',
            method: 'POST',
            headers: {
                'Content-Type': 'application/hal+json',
                'X-CSRF-Token': csrfToken
            },
            data: image,
            success: function(data) {
                console.log('postNode success');
            }
        });
    }

    $('#image-save').click(function() {         //attach fcn to button
        getCsrfToken(function(csrfToken) {
            var $img = $('img[alt="image1"]');  //grab first image
            var imgSrc = $img.attr('src');      //grad base64 source
            imgSrc = imgSrc.replace('data:image/jpeg;base64,',''); //clean
            var package = {
                "_links": {
                    "type": {
                        "href": "http://vhscms/cms/rest/type/file/image"
                    }
                },
                "filename": [{
                    "value": "joggers.jpg"
                }],
                "filemime": [{
                    "value": "image/jpeg"
                }],
                "type": [{
                    "target_id": "image"
                }],
                "uri": [{
                    "value": "public://joggers.jpg"  //forces mime type img
                }],
                "data": [{
                    "value": imgSrc
                }]
            };
            postImage(csrfToken, JSON.stringify(package));
        });
    });


</script>
  • you could use hook_entity_insert to see if type file and then update the status – Taggart Jensen Feb 7 at 2:34

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.