title: upload an image file to sharepoint via api graph
body: <p>I am trying to upload an image file from my node.js application to a group's drive in Sharepoint.</p>
  
  <p>As the <a href="https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0" rel="nofollow noreferrer">official documentation</a> states, I'm making my request as follows:</p>
  
  <pre><code>PUT /groups/{group-id}/drive/items/{parent-id}:/{filename}:/content
  </code></pre>
  
  <p>With the binary image in the body: "The contents of the request body should be the binary stream of the file to be uploaded."</p>
  
  <p>The problem is that the image is uploaded but as a corrupted file. I tried different solutions and still don't see why is always the image corrupted.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>//i get my image from a URL first
  https.get(url.parse(attachment.contentUrl), function (response) {
      var data = [];
      response.on('data', function (chunk) {
          data.push(chunk);
      });
      response.on('end', function () {
        if (response.statusCode === 200) {
          var buffer = Buffer.concat(data);
          //store my image in a local file to test if image is correct (which it is)
          fs.writeFile(localFileName, buffer, (fsError) =&gt; {
              //error handling
          });
          functions.uploadImageToSharepoint(session, localFileName, buffer, 
              function (err, body, res) {
                  if (err) {
                      console.error(err);
                  }else{
                      console.log('OK!');
                  }
              });
        } else {
          //error handling
        }
      });
  }).on('error', function (e) {
      console.log("error2: " + e);
  });
  
  //and the request to graph api
  function uploadImageToSharepoint(session, fileName, data, callback) {
    var options = {
      url: 'https://graph.microsoft.com/v1.0/groups/xxxxxxx/drive/root:/yyyyyy/fileName.jpg:/content', 
      method: 'PUT',
      body: data,
      json: true,
      headers: {
        'Content-Type': 'image/jpg',
        Authorization: 'Bearer ' + session.userData.accessToken
      }    
    };
  
    request(options, function (err, res, body) {
      if (err) return callback(err, body, res);
      if (parseInt(res.statusCode / 100, 10) !== 2) {
          if (body.error) {
              return callback(new Error(res.statusCode + ': ' + (body.error.message || body.error)), body, res);
          }
          return callback(err, body, res);
      }
      callback(err, body ,res);   
    });  
  }
  </code></pre>