javascript - 使用 fetch() 的 WP REST API 媒体上传

标签 javascript wordpress wp-api

我正在尝试使用 fetch() 使用 JS (React Native) 在 WP Rest API 中执行媒体上传。

这是我到目前为止所做的事情:

fetch('https://www.example.fr/wp-json/wp/v2/media', {
        method: 'post',
        headers: new Headers({
          'Content-Type': 'image/jpeg',
          'Authorization': 'Basic d3GtcmVzdC1sdfGktY2xpZW50Onefepbl9hdh90aWJldA==',
          'Content-Disposition': 'attachment; filename="user-'+userId+'.jpg"'
        }),                
        body: imageBase64Data
      })
      .then(function (response) {
        console.log(response);
      });

imageBase64Data 设置如下:

let imageBase64Data = 'data:image/png;base64,'+ imageData;

imageDatareact-native-image-pickerresponse.data:https://github.com/react-community/react-native-image-picker#the-response-object

这是我的问题:在我的 WP 上成功创建了媒体,但图像是空的(没有数据,大约 15B)。所以我猜测我作为请求正文发送的数据出现了问题。但我不知道是什么。

有什么想法吗?

最佳答案

郑重声明,以下是我使用 react-native-fetch-blob 模块最终解决此问题的方法:

 RNFetchBlob.fetch('post', 'https://www.example.fr/wp-json/wp/v2/media', 
      {                    
        'Content-Type': 'image/jpeg',
        'Authorization': 'Basic dqdsfqsdfpbl9hqsdfdsfWJldA==',
        'Content-Disposition': 'attachment; filename="user-'+userId+'.jpg"'
      }

    ,imageUri) // imageUri = RNFetchBlob.wrap(imageUri);
    .then(function (response) {
      console.log(response); // returns a 201 response with id of the attached media
    });    

关于javascript - 使用 fetch() 的 WP REST API 媒体上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44804439/

相关文章:

git - 使用git但不使用git子模块在子目录中安装wordpress

json - Wordpress API json,如何在单个帖子中获取上一篇和下一篇文章?

javascript - 如何在 d3 中的条形图更新数据之间转换?

javascript - 使用 Bootstrap ,将输入文本元素包装在标签中会导致输入文本加粗并且不占用全宽

javascript - 无法让这个 CSS/jQuery 下划线动画工作,我做错了什么?

php - 如何检查 WordPress 中的缩略图?

wordpress - 将联系表 7 与 React 结合使用

wordpress - 在现有的 WordPress 网站上使用react

javascript - 如何将 AjaxRequest 的响应添加到存储或将其显示在列表中

javascript - React 路由器匹配路径问题