【问题标题】:How to upload an image to cloudinary如何将图像上传到 cloudinary
【发布时间】:2018-03-15 09:37:18
【问题描述】:

我想从我的 NodeJS api 上传一张图片到 cloudinary,我有我的模型,在这个模型中我有一个名为 image 的字段,这个字段是字符串类型,在这里我想保存作为响应接收的 url乌云密布。

这是我的 model.js

'use strict';

const mongoose = require('mongoose');

const CursoSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  image: {
    type: String,
  },
  description: {
    type: String,
    required: true
  }
});

module.exports = mongoose.model('Curso', CursoSchema);

还有我的controller.js,这里是我要保存url的地方,我用cloudinary docs的方法试过了。

var imageFile = req.files.image;
cloudinary.uploader.upload(imageFile.path, function(result){
  if (result.url) { res.status(200).send({url: result.url});
  }else {
    console.log('Error uploading to cloudinary');
 }
});

但我刚刚上传了图片。这是我的controller.js

'use strict';

const Curso = require('../models/curso');
const config = require('../config');
const cloudinary = require('cloudinary');

cloudinary.config({
  cloud_name: 'something',
  api_key: 'somthingelse',
  api_secret: 'andotherthing'
})

function saveCurso(req, res) {
  let curso = new Curso();
  let params = req.body;
  curso.name =  params.name;
  curso.description = params.description;
  //How to get the image and upload it to cloudinary

  curso.save((err, cursoSaved)=>{
    if(err){return res.status(500).send({message:'Error'});}
    if(!cursoSaved) return res.status(404).send({message: 'Empty'});
    return res.status(200).send({curso: cursoSaved});
  });
}

module.exports = {
  saveCurso,
}

还有我的 routes.js 文件:

'use strict';

const express = require('express');
const api = express.Router();
const cursoController = require('../controllers/curso');

api.post('/curso', cursoController.saveCurso);

module.exports =  api;

我想保存带有名称、描述和图像的数据,我想保存来自 cloudinary 的 url。

我在 cloudinary 中保存了一些图像,但我找不到在我的图像字段中仅保存 url 的方法

注意:我正在使用 body-parser,这是我的 app.js

'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

const curso_routes = require('./routes/curso');

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.use('/api', curso_routes);

module.exports = app;

【问题讨论】:

    标签: javascript node.js cloudinary


    【解决方案1】:

    首先,您需要使用multermultiparty 之类的包来处理multipart/form-data。所以,使用多方:

    'use strict';
    
    const Curso = require('../models/curso');
    const config = require('../config');
    const cloudinary = require('cloudinary');
    const multiparty = require('multiparty');
    
    cloudinary.config({
      cloud_name: 'something',
      api_key: 'somthingelse',
      api_secret: 'andotherthing'
    })
    
    function saveCurso(req, res) {
    
      //How to get the image and upload it to cloudinary
      let form = new multiparty.Form({ maxFilesSize: 10 * 1024 * 1024 }); //setting max size of image to 10MB
      form.parse(req, (err, fields, files) => {
        if (err) return err
        let curso = new Curso();
        curso.name = fields.name;
        curso.description = fields.description;
        cloudinary.v2.uploader.upload(files.content[0].path, (err, result) => { // content is the name of the image input on the front end form
          if (err) return err
          curso.image = result.secure_url;
          curso.save((err, cursoSaved) => {
            if (err) { return res.status(500).send({ message: 'Error' }); }
            if (!cursoSaved) return res.status(404).send({ message: 'Empty' });
            return res.status(200).send({ curso: cursoSaved });
          });
        });
      }) 
    }
    

    【讨论】:

    • 您向/api/curso 发出发布请求,正文为form-data,然后选择其中一个输入作为文件而不是文本。根据上面的示例,键是“内容”,值是图像。
    • 事实上我做到了,但我只得到了错误,我记录了它,这是我需要的另一个字段
    • 你能解释更多吗?你得到了什么错误?你记录了什么?
    • 这个:if (err) { console.log(err);返回 res.status(500).send({ message: 'Error' });在邮递员中获得响应并在控制台中查看错误在我的控制台中我看到:ValidationError: Curso validation failed: name: Path name is required., description: Path description is required.
    • 当您尝试使用邮递员时,您是发送“名称”和“描述”字段还是仅发送图像?
    【解决方案2】:

    使用纯 HTML JavaScript

    const fileInput = document.getElementById("fileInput");
    const uploading_text = document.getElementById("uploading_text");
    
    // replace with your data ?
    const cloud_name = "demo";
    const upload_preset = "doc_codepen_example";
    // replace with your data ?
    
    fileInput.addEventListener("change", (e) => {
      uploading_text.innerText = "uploading...";
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append("file", file);
      formData.append("upload_preset", upload_preset);
      const options = {
        method: "POST",
        body: formData,
      };
    
      return fetch(
        `https://api.cloudinary.com/v1_1/${cloud_name}/image/upload`,
        options
      )
        .then((res) => res.json())
        .then((data) => {
          // url ?
          console.log(data.secure_url);
    
          uploading_text.innerHTML = `
          <span>upload complete.</span>
          <br />
          <img style="max-width:300px" src="${data.secure_url}" alt="">
          <a href="${data.secure_url}">${data.secure_url}</a>
          `;
        })
        .catch((err) => console.log(err));
    });
    <input type="file" id="fileInput" />
        
    <p id="uploading_text"></p>

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2021-03-20
      • 2017-08-04
      • 2015-02-21
      • 2017-07-12
      • 2014-11-25
      • 2020-10-18
      • 2016-04-28
      • 2021-10-10
      相关资源
      最近更新 更多