如何上传图片到cloudinary

How to upload an image to cloudinary

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

这是我的 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;

首先你需要使用像 multer or multiparty 这样的包来处理 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 });
      });
    });
  }) 
}

with plain 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>