这个 Upload documentation 是我能找到的所有使用 FormData api 的基于浏览器的示例。
它所声明的只是您 POST
到 /uploads
和 files
类型的缓冲区/流参数。这是我目前所处的位置:
fs.readFile(filepath, (err, data) => {
needle('post','http://localhost:1337/upload', {files: data}, {
multipart: true,
}).then(response => {
console.log(response.body);
if(response.body.data)
console.log(response.body.data.errors)
});
});
发布成功,但有些地方不太对劲,图片已注册但在媒体库中丢失,名称为“文件”而不是任何有意义的名称。
帖子回复示例:
[
{
id: 170,
name: 'files',
alternativeText: null,
caption: null,
width: 768,
height: 1024,
formats: {
thumbnail: [Object],
large: [Object],
medium: [Object],
small: [Object]
},
hash: 'files_d98a49e7f5',
ext: '',
mime: 'application/octet-stream',
size: 159.62,
url: '/uploads/files_d98a49e7f5',
previewUrl: null,
provider: 'local',
provider_metadata: null,
created_at: '2021-06-09T17:12:52.951Z',
updated_at: '2021-06-09T17:12:52.951Z',
related: []
}
]
我还尝试使用节点模块 form-data
来模仿文档中提供的示例。
let form = new FormData();
form.append('files', fs.createReadStream("./test.jpg"))
let data = form //attempt1
let data = {files: form} //attempt2
let data = {files: form.toString()} //attempt3
needle('post','http://localhost:1337/upload', data, {
multipart: true,
})
但这通常会返回 400 个错误的请求,响应如下:
{ id: 'Upload.status.empty', message: 'Files are empty' }
答案 0 :(得分:0)
用 needle 模块提供的 submit
方法替换 form-data http 请求,如下所示:
let form = new FormData();
form.append('files', fs.createReadStream("./testimage.jpg"))
form.append('fileInfo', JSON.stringify({
alternativeText: 'example'
}));
form.submit('http://localhost:1337/upload', (err,res) => {
res.on('data', function (chunk) {
console.log(JSON.parse(chunk)) //response file object
});
})