Nodejs 使用 FormData 将文件上传到 Strapi
Posted
技术标签:
【中文标题】Nodejs 使用 FormData 将文件上传到 Strapi【英文标题】:Nodejs Upload File to Strapi Using FormData 【发布时间】:2020-06-10 11:51:03 【问题描述】:你好,我在从后端 nodejs 上传文件到strapi时遇到问题,我正在做
bodyFormData.append('files.image', fs.createReadStream(req.file.path), req.file.filename);
bodyFormData.append('data', JSON.stringify(data));
并使用 axios 创建一个 post 请求
axios(
url:`$strapi/campaigns`,
method:'post',
data:bodyFormData,
withCredentials:true,
)
.then(response=>
console.log(response.data)
// return res.status(200).send(response.data)
)
.catch(err=>
res.status(400).send(err)
)
这是我的 console.log(bodyFormData)
FormData
[0] _overheadLength: 288,
[0] _valueLength: 272,
[0] _valuesToMeasure: [],
[0] writable: false,
[0] readable: true,
[0] dataSize: 0,
[0] maxDataSize: 2097152,
[0] pauseStreams: true,
[0] _released: false,
[0] _streams: [
[0] '----------------------------167862620653181372969530\r\n' +
[0] 'Content-Disposition: form-data; name="files.image"; filename="1582728780533-fancy-bottom-border.png"\r\n' +
[0] 'Content-Type: image/png\r\n' +
[0] '\r\n',
[0] 'public\\1582728780533-fancy-bottom-border.png',
[0] [Function: bound ],
[0] '----------------------------167862620653181372969530\r\n' +
[0] 'Content-Disposition: form-data; name="data"\r\n' +
[0] '\r\n',
[0] '"title":"123`$strapi/campaigns`","description":"`$strapi/campaigns`","author":"id":62,"reference":30939226,"goal":"123","verified":false,"deleted":false,"requested":false,"raised":0,"username":"cjoyales","currency":"USD"',
[0] [Function: bound ]
[0] ],
[0] _currentStream: null,
[0] _insideLoop: false,
[0] _pendingNext: false,
[0] _boundary: '--------------------------167862620653181372969530'
[0]
但这是来自strapi的console.log(response.data)
[0] id: 176,
[0] title: '',
[0] description: '',
[0] goal: 0,
[0] raised: null,
[0] username: null,
[0] created_at: '2020-02-26T14:53:00.000Z',
[0] updated_at: '2020-02-26T14:53:00.000Z',
[0] verified: null,
[0] deleted: null,
[0] author: null,
[0] reference: null,
[0] currency: null,
[0] requested: null,
[0] done: null,
[0] image: [],
[0] supporters: []
[0]
为什么即使表单数据中有值,它也为空或null?有人可以帮忙吗?谢谢
【问题讨论】:
您好!你在strapi.io/documentation/3.0.0-beta.x/plugins/upload.html 那里检查过 JS 示例吗? 是的,我已经检查了文档 .. 后端收到了数据,但是当后端通过 post 请求将数据发送到strapi ...后端从strapi接收空值或空值 【参考方案1】:尝试替换
bodyFormData.append('files.image', fs.createReadStream(req.file.path), req.file.filename);
与
bodyFormData.append('files', fs.createReadStream(req.file.path), req.file.filename);
在我读到 Pavlo Razumovskyi 的评论 here 之前,我为类似的事情苦苦挣扎了好几个小时:
现在是新的 api,请查看新文档: Strapi.io/documentation/3.0.0-beta.x/plugins/… formData.append('files.MODEL_FILE_FIELD_NAME', blob, 文件名)
【讨论】:
以上是关于Nodejs 使用 FormData 将文件上传到 Strapi的主要内容,如果未能解决你的问题,请参考以下文章
将文件附加到 FormData 在 angularjs 中不起作用
如何在 formData 对象中附加文件而不在 Node.js 中物理保存文件?
由于 CORS,使用 createPresignedPost 或 getPresignedUrl 将 formData 文件从客户端上传到 S3 失败