skip to Main Content

I managed to upload an image to facebook using online URL but, when I try a local image using format file://path/to/imageI get the error

{"error":{"message":"(#100) url should represent a valid URL","type":"OAuthException","code":100}

is it doable ? or am doing it wrong ?

async function upload_fb_image(photo) {

    return new Promise(resolve => {

        FB.api(PAGE_ID + '/photos', 'post', {
            message: 'Message',
            url: LINK_TO_IMAGE,
            published: false,
            caption: 'Ad',
            access_token: EXD_ACCESS_TOKEN
        }).then(data => { resolve(data) })
    })
}

as Form data

I tried as form data as mentioned in answers … I receive ok response but, the image ID is not returned, I get the below JSON in reponse

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]:
   { body:
      PassThrough {
        _readableState:
         ReadableState {
           objectMode: false,
           highWaterMark: 16384,
           buffer: BufferList { head: [Object], tail: [Object], length: 1 },
           length: 25,
           pipes: null,
           pipesCount: 0,
           flowing: null,
           ended: true,
           endEmitted: false,
           reading: false,
           sync: false,
           needReadable: false,
           emittedReadable: false,
           readableListening: false,
           resumeScheduled: false,
           paused: true,
           emitClose: true,
           autoDestroy: false,
           destroyed: false,
           defaultEncoding: 'utf8',
           awaitDrain: 0,
           readingMore: false,
           decoder: null,
           encoding: null },
        readable: true,
        _events:
         [Object: null prototype] {
           prefinish:
            { [Function: prefinish]
              [length]: 0,
              [name]: 'prefinish',
              [prototype]: prefinish { [constructor]: [Circular] } },
           error:
            { [Function]
              [length]: 1,
              [name]: '',
              [prototype]: { [constructor]: [Circular] } } },
        _eventsCount: 2,
        _maxListeners: undefined,
        _writableState:
         WritableState {
           objectMode: false,
           highWaterMark: 16384,
           finalCalled: false,
           needDrain: false,
           ending: true,
           ended: true,
           finished: true,
           destroyed: false,
           decodeStrings: true,
           defaultEncoding: 'utf8',
           length: 0,
           writing: false,
           corked: 0,
           sync: false,
           bufferProcessing: false,
           onwrite:
            { [Function: bound onwrite] [length]: 1, [name]: 'bound onwrite' },
           writecb: null,
           writelen: 0,
           bufferedRequest: null,
           lastBufferedRequest: null,
           pendingcb: 0,
           prefinished: true,
           errorEmitted: false,
           emitClose: true,
           autoDestroy: false,
           bufferedRequestCount: 0,
           corkedRequestsFree:
            { next: null,
              entry: null,
              finish:
               { [Function: bound onCorkedFinish] [length]: 1, [name]: 'bound onCorkedFinish' } } },
        writable: false,
        allowHalfOpen: true,
        _transformState:
         { afterTransform:
            { [Function: bound afterTransform] [length]: 2, [name]: 'bound afterTransform' },
           needTransform: false,
           transforming: false,
           writecb: null,
           writechunk: null,
           writeencoding: 'buffer' } },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]:
   { url: 'https://graph.facebook.com/page_id/photos',
     status: 200,
     statusText: 'OK',
     headers:
      Headers {
        [Symbol(map)]:
         [Object: null prototype] {
           'x-business-use-case-usage':
            [ '{"1006471116044666":[{"type":"pages","call_count":1,"total_cputime":1,"total_time":1,"estimated_time_to_regain_access":0}]}',
              [length]: 1 ],
           'content-type': [ 'application/json; charset=UTF-8', [length]: 1 ],
           'facebook-api-version': [ 'v2.10', [length]: 1 ],
           'strict-transport-security': [ 'max-age=15552000; preload', [length]: 1 ],
           pragma: [ 'no-cache', [length]: 1 ],
           'x-fb-rev': [ '1001316471', [length]: 1 ],
           'access-control-allow-origin': [ '*', [length]: 1 ],
           'cache-control':
            [ 'private, no-cache, no-store, must-revalidate', [length]: 1 ],
           'x-fb-trace-id': [ 'CSSaQru0iZZ', [length]: 1 ],
           'x-fb-request-id': [ 'AguAWIpbfPySfVvwPjZZBec', [length]: 1 ],
           expires: [ 'Sat, 01 Jan 2000 00:00:00 GMT', [length]: 1 ],
           'x-fb-debug':
            [ 'NnSTSun7s8VUcMnXu9cUYXQh/7laST0pILTNbAJrS0mtGHGXnQt17fRtyhS8R+RkZWyawJ4meKDWNKT1N+1uBA==',
              [length]: 1 ],
           date: [ 'Sat, 19 Oct 2019 01:31:32 GMT', [length]: 1 ],
           'x-fb-trip-id': [ '1886706526', [length]: 1 ],
           'alt-svc': [ 'h3-23=":443"; ma=3600', [length]: 1 ],
           connection: [ 'close', [length]: 1 ],
           'content-length': [ '25', [length]: 1 ] } },
     counter: 0 } }

2

Answers


  1. Chosen as BEST ANSWER

    finally it was solved using the below method

     const formData = {
                access_token: EXD_ACCESS_TOKEN,
                source: fs.createReadStream("path/to/image"),
                published: 'false'
            }
    
            console.log('sendning request')
    
            request.post({ url: `https://graph.facebook.com/${PAGE_ID}/photos`, formData: formData }, function optionalCallback(err, httpResponse, body) {
                if (err) {
                    return console.error('upload failed:', err);
                }
    
                resolve(body)
            });
    

  2. The url must be a public url, not some url from your local computer. Alternatively, you can use FormData:

    const fileReader = new FileReader();
    const file = document.getElementById('imageInput').files[0];
    
    fileReader.onloadend = async () => {
        const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
        const formData = new FormData();
    
        formData.append('access_token', pageAccessToken);
        formData.append('source', photoData);
        formData.append('message', 'some status message');
    
        let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
            body: formData,
            method: 'post'
        });
        response = await response.json();
        console.log(response);
    };
    fileReader.readAsArrayBuffer(file);
    

    Source: https://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search