【发布时间】:2019-01-04 19:25:28
【问题描述】:
我正在尝试使用 Wordpress rest API 将图像上传到 wordpress。
一切正常,但没有上传正确的图像。但是,当我使用卷曲图像时是正确的。
curl --request POST \
--url http://localhost/wordpress/wp-json/wp/v2/media/ \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=hh.jpg" \
--header "authorization: Basic token" \
--header "content-type: image/jpg" \
--data-binary "@C://Users/as/Desktop/App _Ideas/hh.jpg" \
此 curl 请求工作正常。
现在,当我将请求转换为 Nodejs 时
request({
url: ' http://localhost/wordpress/wp-json/wp/v2/media/',
headers: {
'cache-control': 'no-cache',
'content-disposition': 'attachment; filename='+filename,
'content-type' : 'image/jpg',
'authorization' : 'Basic token'
},
encoding: null,
method: 'POST',
body: "@C://Users/as/Desktop/App _Ideas/hh.jpg",
encoding: null
}, (error, response, body) => {
if (error) {
res.json({name : error});
} else {
res.json(JSON.parse(response.body.toString()));
}
});
当 imge 上传时,我能够从 wordpress 接收 json 响应。但是,上传的图像不正确,因为传递的二进制数据不正确。
Wordpress 上传文件夹显示文件hh.jpg 大小为 17 字节。使用记事本编辑时显示@hh.jpg,这意味着字符串数据保存为 hh.jpg 而不是实际的二进制数据。
关于如何使用 Nodejs 正确传递二进制数据的任何想法。
【问题讨论】:
-
是的......你传递的身体是一个字符串。我猜
@path是 curl 的语法糖。 -
@alex-rokabilis 是的,你是对的。在使用记事本编辑上传的图像时,它显示 hh.jpg 表示由于 content-disposition 标头而将字符串另存为图像。
-
知道如何正确上传吗?
-
是的,试试
body: require('fs').createReadStream("C://Users/as/Desktop/App _Ideas/hh.jpg")(我不确定windows中路径的正确格式,也许你需要反斜杠?)
标签: node.js