从Telegram取图片通过Axios上传至Strapi时遇异常求助
解决Strapi图片上传无内容/400错误的方案
问题根源
- 手动设置
Content-Type: multipart/form-data会丢失Axios自动生成的boundary分隔符,导致Strapi无法正确解析FormData里的文件内容,所以返回200但文件无实际内容。 - 文件上传时未指定正确的文件名和MIME类型,Strapi无法识别文件格式。
- 多余的
Buffer.from(axres.data)转换,因为responseType: 'buffer'已经返回Buffer类型数据。
修正后的代码
return bot.getFileLink(msg.photo[0].file_id).then((resp) => { axios.get(resp, { responseType: 'buffer' }) // 直接获取Buffer格式的图片数据 .then(axres => { const imgdata = new FormData(); // 关键:指定文件名、MIME类型,直接使用已有的Buffer数据 imgdata.append('files', axres.data, { filename: `telegram-image-${Date.now()}.jpg`, contentType: 'image/jpeg' }); axios.post(`http://localhost:1337/api/upload`, imgdata) .then(response => { console.log('上传成功:', response.data); }) .catch(err => { console.error('上传失败:', err.response?.data || err.message); }); }); });
额外说明
- 不要手动设置
multipart/form-data头:Axios检测到请求体是FormData时,会自动生成包含boundary的正确Content-Type头,手动设置会破坏这个逻辑。 - 指定MIME类型:根据你上传的图片类型(比如png就用
image/png)设置contentType,确保Strapi能正确识别文件类型。 - 文件名尽量简洁:不要用完整的Telegram链接当文件名,用自定义的有意义名称,避免路径或特殊字符问题。
内容的提问来源于stack exchange,提问作者Алексей Пащенко
相关产品推荐
相关产品推荐

