5

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>
2

1 Answer 1

1

Suggestions

  • I think filemime is autogenerated depending on the file you're uploading.
  • To make the file permanent, have you tried sending the property status: [value: 1]?
    • A status of 1 indicates that the file is permanent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.