【问题标题】:Upload images into a file server and store the url to the image using nodejs将图像上传到文件服务器并使用 nodejs 将 url 存储到图像
【发布时间】:2018-11-01 15:25:33
【问题描述】:

我正在使用MEAN StackAngular 6 实现一个网络应用程序。在那里我想提交一个带有文件上传的表单。 '.png' 文件应该被上传。

我想将文件保存在不同的文件服务器中并将 url 发送到图像。目前我将文件上传到项目中的文件夹并将图像保存在 db 中(为此我使用了 ng2fileuploadmulter .)。然后它像这样保存。

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAV4AAAFUCAYAAABssFR8AAAK..."

但我想保存图像 url,并且图像应该由 url 检索。有没有人可以解释一个正确的方法?

【问题讨论】:

  • 您可以使用 Cloudinary 服务

标签: node.js angular mean-stack ng2-file-upload


【解决方案1】:

一个月前我遇到了同样的问题,并找到了解决这个问题的方法。虽然我没有在应用程序中使用multer

  1. 从我的前端,我将向 Node API 端点 /event 发送一个对象,如下所示:-

let img = { content: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...", filename: 'yourfile.png' }

  1. 在后端,我使用Cloudinary 来存储我的图像(其免费计划允许 10GB 存储空间)并返回安全的 https URL。所以使用npm i cloudinary 安装它并在你的api.js 文件中要求。 并添加以下配置

    cloudinary.config({ cloud_name: 'yourapp', api_key: 'YOUR_KEY', api_secret: 'YOUR_SECRET_KEY' });

最后一步:-(没有那么优化的代码)

假设我有一个 事件架构,其中包含图像数组,我将在其中存储 cloudinary 返回的 URL。

app.post('/event', (req, res) => {
    try {
        if (req.body.images.length > 0) {

           // Creating new Event instance

            const event = new Event({
                images: [],
            });

           // Looping over every image coming in the request object from frontend
            req.body.images.forEach((img) => {
                const base64Data = img.content.split(',')[1];

            // Writing the images in upload folder for time being 
                fs.writeFileSync(`./uploads/${img.filename}`, base64Data, 'base64', (err) => {
                    if (err) {
                        throw err;
                    }
                });

              /* Now that image is saved in upload folder, Cloudnary picks 
             the image from upload folder and store it at their cloud space.*/
                cloudinary.uploader.upload(`./uploads/${img.filename}`, async (result) => {

                 // Cloudnary returns id & URL of the image which is pushed into the event.images array.
                    event.images.push({
                        id: result.public_id,
                        url: result.secure_url
                    });

                 // Once image is pushed into the array, I'm removing it from my server's upload folder using unlinkSync function
                    fs.unlinkSync(`./uploads/${img.filename}`);

       // When all the images are uploaded then I'm sending back the response
                    if (req.body.images.length === event.images.length) {
                        await event.save();
                        res.send({
                            event,
                            msg: 'Event created successfully'
                        });
                    }
                });
            });
        }
    } catch (e) {
        res.status(400).send(e);
    }
});

P.S.继续为这段代码提出一些优化解决方案here

【讨论】:

猜你喜欢
  • 2015-03-02
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2021-05-03
  • 2011-11-18
  • 2016-06-06
  • 2014-05-09
相关资源
最近更新 更多