admin管理员组文章数量:1279175
I'm building a CSV importer for my Strapi application and one of its task is to read an image URL from a cell and download it from the URL and save it to media library.
The code looks like this:
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'
}
});
});
The download works and I get a Buffer in the body
variable of the request.get
callback. But passing this to strapi.plugins.upload.services.upload.upload
give me the following error:
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 ...
I already tried to replace path: body,
with path: new Uint8Array(body),
but without no luck.
Any idea what I do wrong here?
Thanks for your help!
I'm building a CSV importer for my Strapi application and one of its task is to read an image URL from a cell and download it from the URL and save it to media library.
The code looks like this:
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'
}
});
});
The download works and I get a Buffer in the body
variable of the request.get
callback. But passing this to strapi.plugins.upload.services.upload.upload
give me the following error:
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 ...
I already tried to replace path: body,
with path: new Uint8Array(body),
but without no luck.
Any idea what I do wrong here?
Thanks for your help!
Share Improve this question asked Jan 11, 2022 at 23:43 Hermann DettmannHermann Dettmann 2402 silver badges12 bronze badges 1- It's pretty clear that the function expects a file pathname, not a buffer. – Ouroborus Commented Jan 12, 2022 at 1:59
1 Answer
Reset to default 12I had this exact same requirement in one of my projects where I had to fetch a file from an URL
and then upload it to media library. I've approached the problem by first fetching the stream of bytes from the URL
and then saving it to a file in a tmp
folder. Once the file is fully downloaded, I've simply used the inbuilt upload
method of strapi
to upload the file to the media library.
Libraries you need to install
$ npm install mime-types
$ npm install axios
$ npm install lodash
Implementation
// 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);
},
};
Then in you're actual service/controller you can simply invoke the method from your helper like so:
const uploader = require('../../../helpers/uploader');
const img = await uploader.uploadToLibrary('http://www.example./demo-image.jpg');
console.log(img);
References:
- Mime-Types
- Axios
- Lodash
本文标签: javascriptLoad image from URL and upload to media library in StrapiStack Overflow
版权声明:本文标题:javascript - Load image from URL and upload to media library in Strapi - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741277232a2369801.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论