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
    you could use hook_entity_insert to see if type file and then update the status Commented Feb 7, 2019 at 2:34
  • 1
    See my answer here: drupal.stackexchange.com/questions/298977/… Commented Dec 28, 2020 at 21:27

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.