如何使用NodeJ在https://api.linkedin.com/mediaUpload/上放置媒体 [英] How to PUT media on https://api.linkedin.com/mediaUpload/ with NodeJs

查看:45
本文介绍了如何使用NodeJ在https://api.linkedin.com/mediaUpload/上放置媒体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我呼叫路由 https://api.linkedin.com/v2/asset?action = registerUpload 与axios

When I call the route https://api.linkedin.com/v2/assets?action=registerUpload with axios

我有这样的回复

{
    "value": {
        "uploadMechanism": {
            "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest": {
                "uploadUrl": "https://api.linkedin.com/mediaUpload/C4E22AQGSNx_ko_tzLw/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQK-VkaHKm7-NQAAAXMad6RKlbsQGW9Vi3JI0iFnlEKhTdhVcSZxyxUJ5g&app=17412253&sync=1&v=beta&ut=0MQzOzxqQ7m9k1",
                "headers": {
                    "media-type-family": "STILLIMAGE"
                }
            }
        },
        "asset": "urn:li:digitalmediaAsset:C4E22QSGSNx_ko_tzLw",
        "mediaArtifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:C4E22AQGSNx_ko_tzLw,urn:li:digitalmediaMediaArtifactClass:feedshare-uploadedImage)"
    }
}

我想使用上传链接从服务器上传图像

I want to upload an image from my server with the upload link

 var newFile = fs.createReadStream(__dirname+"/temp/lion.png");

 const form_data = new FormData();
 form_data.append('file', newFile);
 const request_config = {
      headers: {
        'Authorization': `Bearer ${access_token}`,
        "Content-Type": "multipart/form-data"
      },
      data: {content : form_data['_streams']['1']}
    };

    const res = await  axios.put('https://api.linkedin.com/mediaUpload/C4E2OIQNQE5ILcQCU_lLA/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQIy5jpkZ0ut2AAAAXMadpS8A97cK9wOSjzagaNHo97bRPCYVZt7f5E4yQ&app=17411153&sync=1&v=beta&ut=2JZ18aO4E6m9k1', form_data, request_config);
    

但是我收到服务器的回复

But I have this response from the server

"Error: Request failed with status code 400\n    at createError (/home/node/app/node_modules/axios/lib/core/createError.js:16:15)\n    at settle (/home/node/app/node_modules/axios/lib/core/settle.js:17:12)\n    at IncomingMessage.handleStreamEnd (/home/node/app/node_modules/axios/lib/adapters/http.js:236:11)\n    at IncomingMessage.emit (events.js:198:15)\n    at endReadableNT (_stream_readable.js:1139:12)\n    at processTicksAndRejections (internal/process/task_queues.js:81:17)"

推荐答案

7个月大的问题,但今天仍然是一个问题,试图花数小时来弄清楚这个问题.

7 Months old question, but still an issue today, was trying to figure this thing for few hours.

如果仅Linkedin可以添加(如普通API)他们希望获得的信息(如Content-Type标头或采用哪种编码),本来可以容易得多.

Could have been much easier if only Linkedin would add (like a normal API) the information they expect to get, like the Content-Type header, or what encoding.

我有一个需要上传为图片的URL,所以我做了一些额外的步骤,但是一般的想法是您需要包含图片的Content-Type,使用它们给您的URL发送文件,并以ArrayBuffer的形式获取文件,并且不要忘记使用PUT方法.

I have a URL I need to upload as an image, so I have do some extra steps, but the general idea is you need to include the Content-Type of your image, use the URL they give you to send the file, and get the file as ArrayBuffer, as well as not forget to use the PUT method.

获取ArrayBuffer并获取文件的内容类型:

to get ArrayBuffer, and get the content type of the file:

axios.get(imageUrl, {responseType: 'arraybuffer'}).then((imageData) => {
    const contentType = imageData.headers['content-type'];
    //The ArrayBuffer is at imageData.data
})

注意- 不要忘记包含 supportedUploadMechanism:['SYNCHRONOUS_UPLOAD'] ,这样它将同步上传,您赢了不必发送其他请求来确保上传成功完成.

NOTE- Don't forget to include supportedUploadMechanism: ['SYNCHRONOUS_UPLOAD'], so the it will upload synchronously, and you won't have to send another request to make sure the upload was done successfully.

const registerUploadRequest = {
        owner:                    this.owner,
        recipes:                  ['urn:li:digitalmediaRecipe:feedshare-image'],
        serviceRelationships:     [
          {
            identifier:       'urn:li:userGeneratedContent',
            relationshipType: 'OWNER',
          },
        ],
        supportedUploadMechanism: ['SYNCHRONOUS_UPLOAD'],
      };

获取所需的图像数据后,我将请求发送到/assets?action = registerUpload ,以便获取资产的ID以及将其上传到的URL:

After I got the image data I need, I send request to /assets?action=registerUpload so I can get the id of the asset, as well as the URL I need to upload it to:

return this.post('/assets?action=registerUpload', {registerUploadRequest}).then((result) => {
        const url     = result.value.uploadMechanism['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest'].uploadUrl,
              assetId = result.value.asset.replace('urn:li:digitalmediaAsset:', '');
})

注意-上传后,我们需要ID才能使用资产.

Note - we need the id to use the asset after upload.

最终获得所需的所有数据后,我只需将ArrayBuffer放入具有正确内容类型的给定URL.

After I finally got all the data I need, I simply PUT the ArrayBuffer to the url given, with the correct content-type.

return axios.put(url, imageData.data, {
          headers: {
            'Authorization': `Bearer ${this.accessToken}`,
            'Content-Type':  contentType,
          },
        })

您完成了.

重要-他们不会在数据对象中发送任何响应,如果请求成功,则上传的图像成功,如果失败,则失败.

IMPORTANT - they do not send any response in the data object, if the request was successful the image uploaded, if it failed, it didn't.

这篇关于如何使用NodeJ在https://api.linkedin.com/mediaUpload/上放置媒体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆