Her*_*ann 4 javascript node.js server strapi
我正在为我的 Strapi 应用程序构建一个 CSV 导入器,其任务之一是从单元格读取图像 URL 并从该 URL 下载它并将其保存到媒体库。
代码如下所示:
const request = require('request').defaults({ encoding: null });
request.get(src, function (err, res, body) {
const fileName = src.split('/').pop();
strapi.plugins.upload.services.upload.upload({
files: {
path: body,
name: fileName,
type: res.headers['content-type'],
size: Number(res.headers['content-length']),
},
data: {
ref: 'products',
refId: data.itemID,
field: 'images'
}
});
});
Run Code Online (Sandbox Code Playgroud)
下载工作正常,我在回调body的变量中得到一个缓冲区request.get。但传递这个strapi.plugins.upload.services.upload.upload给我以下错误:
UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received <Buffer ff d8 ff e1 10 c1 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 0f 00 00 01 03 00 01 00 00 00 6c 05 00 00 01 01 03 00 01 00 ...
Run Code Online (Sandbox Code Playgroud)
我已经尝试更换path: body,但path: new Uint8Array(body),没有运气。
知道我在这里做错了什么吗?
感谢您的帮助!
Sal*_*'sa 11
我在我的一个项目中也有同样的要求,我必须从媒体库中获取文件URL,然后将其上传到媒体库。我通过首先从 中获取字节流URL,然后将其保存到tmp文件夹中的文件来解决这个问题。文件完全下载后,我只需使用内置upload方法strapi将文件上传到媒体库。
$ npm install mime-types
$ npm install axios
$ npm install lodash
// my-project/helpers/uploader.js
const _ = require('lodash');
const axios = require('axios').default;
const fs = require('fs');
const stream = require('stream');
const path = require('path');
const promisify = require('util').promisify;
const mime = require('mime-types');
module.exports = {
getFileDetails(filePath) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, stats) => {
if (err) reject(err.message);
resolve(stats);
});
});
},
deleteFile(filePath) {
return new Promise((resolve, reject) => {
fs.unlink(filePath, (err) => {
if (err) reject(err.message);
resolve('deleted');
});
});
},
async uploadToLibrary(imageByteStreamURL) {
const filePath = './tmp/myImage.jpeg';
const { data } = await axios.get(imageByteStreamURL, {
responseType: 'stream',
});
const file = fs.createWriteStream(filePath);
const finished = promisify(stream.finished);
data.pipe(file);
await finished(file);
const image = await this.upload(filePath, 'uploads');
return image;
},
async upload(filePath, saveAs) {
const stats = await this.getFileDetails(filePath);
const fileName = path.parse(filePath).base;
const res = await strapi.plugins.upload.services.upload.upload({
data: { path: saveAs },
files: {
path: filePath,
name: fileName,
type: mime.lookup(filePath),
size: stats.size,
},
});
await this.deleteFile(filePath);
return _.first(res);
},
};
Run Code Online (Sandbox Code Playgroud)
然后在您实际的服务/控制器中,您可以简单地从助手中调用该方法,如下所示:
const uploader = require('../../../helpers/uploader');
const img = await uploader.uploadToLibrary('http://www.example.com/demo-image.jpg');
console.log(img);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5555 次 |
| 最近记录: |