【问题标题】:How to upload multiple images on imageKit from nodeJs app?如何从 nodeJs 应用程序在 imageKit 上上传多个图像?
【发布时间】:2022-03-23 09:57:48
【问题描述】:

我正在尝试通过 HTML 表单提交的图像,然后通过节点应用程序将它们上传到 imagekit 中。我完全迷失了配置。任何帮助将不胜感激。

const app = express();
const multer = require('multer');
const path = require('path');
const upload = multer({
    dest: "uploads/" // "uploads"
});


var ImageKit = require("imagekit");
var fs = require('fs');


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended: true}));


var imagekit = new ImageKit({
    publicKey : "public_6ImvGNsOViPhZ*******",
    privateKey : "private_IZ1pjwUR9F********",
    urlEndpoint : "https://ik.imagekit.io/*****/"
});




app.get('/upload', (req, res) => {
    res.render('index')
})

app.post('/upload', upload.single("image"), (req, res) => {
    fs.readFile('uploads/' + req.file.filename, function(err, data) {
        if (err) throw err; // Fail if the file can't be read.
        imagekit.upload({
          file : req.file, //required
          fileName : req.file.filename + '.jpg', //required
          tags: ["tag1", "tag2"]
        }, function(error, result) {
          if(error) console.log(error);
          else console.log(result);
        });
      });
    console.log(req.file.filename);
    res.redirect('/upload');
})

【问题讨论】:

  • 您遇到了什么错误?

标签: node.js imagekit


【解决方案1】:

您不需要将图像发送到节点应用程序然后上传它们,您可以使用后端身份验证端点直接从客户端上传图像。您可以为此使用imagekit-javascript sdk。 它还有一个sample app,您可以参考。

【讨论】:

    【解决方案2】:

    首先为 Multer 设置一个中间件,并在其中将存储目标设置为内存:

        module.exports=(req, res, next) =>{
        const uploadFiles = multer({storage:multer.memoryStorage()}).single('image'); //'image' = the input name  in will be in the form
        uploadFiles(req, res, err => {
            if (err instanceof multer.MulterError) { // A Multer error occurred when uploading.
                if (err.code === "LIMIT_UNEXPECTED_FILE") { // Too many images exceeding the allowed limit
                // ...
                }
            } else if (err) {
                // handle other errors
            }
        
            // Everything is ok.
            next();
        });
    }
    

    然后在您的帖子请求中执行以下操作:

        exports.addImage = async (req, res, next) => {
    
        await imagekit.upload({
            file : req.file.buffer, //required
            fileName : req.file.originalname, //required
            folder:'myFolder', // optional
          }, function(error, result) {
            if(error) console.log(error);
            else
            return res.status(200).json({
                message:result
            })
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2016-04-14
      • 2020-03-23
      • 2011-02-20
      相关资源
      最近更新 更多