0

I create a REST server with Drupal 7, set everything and it work correctly, node created well, but I want to fill File field with REST.

my client side code is the following.

(function($){
  function getCsrfToken(callback) {
  jQuery.get(('http://example.com//services/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://example.com/rest/node',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  type:'video',
  title: 'Example node title3',
  body: {
    und: {
    0: {
    value :"Body"}
       }
    },
  field_url:{   
   und: {
     0: {
      value :"http://url.com"
    }
    }
    },
field_video:{
 ???????
 }
}; 

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});
  })(jQuery);

How can I pass a file (or an image) to REST service? what should I write instead of ??????

2 Answers 2

1

You could upload the file first using the file:create_raw services resource, which will return a file id (fid). Then you create your node and pass the fid in the file field {fid: "x}:

var data = new FormData();
data.append('files[file_1]', file);

jQuery.ajax({
    url: 'http://example.com/rest/file/create_raw',
    data: data,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(result){
        alert(result);
    }
});
4
  • can you provide more details or an example or useful example link?
    – Yuseferi
    Commented Jul 6, 2016 at 13:23
  • I have added some sample code
    – Stéphane
    Commented Jul 6, 2016 at 17:06
  • thanks, what is data, base64decode of file?
    – Yuseferi
    Commented Jul 6, 2016 at 19:08
  • @zhilevan, no data's type is FormData which provides a way to easily construct a set of key/value pairs representing form fields. files[file_1] is the key and file contains the raw file, either from HTML form file input , or a Blob, s. Using FormData Objects
    – Stéphane
    Commented Jul 7, 2016 at 10:37
0

You will want to base64 encode the image file before you submit your document to the REST endpoint.

You an use https://www.base64encode.org/ to get an sample encoded image.

1
  • I know it is base64 file, but how to pass to Drupal REST( with which format)? provide your answer according to my question please.
    – Yuseferi
    Commented Jun 6, 2016 at 13:57

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.