How to upload multiple images to Cloudinary? - node.js

I've implemented a working post route that uploads a single image to cloudinary on submit.
What needs to be changed to enable multiple image upload? Any help is appreciated.
My post route:
app.post("/portfolio/new", upload.single('image'), function(req, res) {
cloudinary.v2.uploader.upload(req.file.path, function(err, result) {
if (err) {
console.log(err);
}
req.body.image = result.secure_url;
console.log(req.body.image);
Portfolio.create(req.body.project, function(err, newProject) {]
if (err) {
console.log(err);
}
res.redirect("/portfolio");
});
});
});
My HTML (with EJS):
<form action="/portfolio/new" enctype="multipart/form-data" method="POST">
<div>
Select images:
<input type="file" id="image" name="image" accept="image/*" required>
</div>
</form>

const cloudinaryImageUploadMethod = async file => {
return new Promise(resolve => {
cloudinary.uploader.upload( file , (err, res) => {
if (err) return res.status(500).send("upload image error")
resolve({
res: res.secure_url
})
}
)
})
}
router.post("/", upload.array("img", 3 ), async (req, res) => {
const urls = [];
const files = req.files;
for (const file of files) {
const { path } = file;
const newPath = await cloudinaryImageUploadMethod(path);
urls.push(newPath);
}
const product = new Product({
name: req.body.name,
productImages: urls.map( url => url.res ),
});
}

To add to the above, you can use this pen for a simple javascript multiple image uploader: codepen.io/team/Cloudinary/pen/QgpyOK
Here's a very fancy uploader widget with a ton of options built-in: codepen.io/dzeitman/pen/EwgjJV
Hope this helps others trying to do something similar and just want to see something working.

in input tag, you should write ... multiple.
and in post route, one should write
upload.array("image")
instead of
upload.single()
and in the schema file, you should define the image as an array of objects
i.e. image:[
{
URL: String,
filename: String
}
]

Related

Node / React : I can't upload an image with my post with multer

I'm trying to create a small social network in which we can send posts (with or without images).
I manage to create posts without an image (just text), it works very well, but as soon as I add an image to my form and submit the form, it is impossible to find the image. Normally it should be saved in the "images" folder but it is always empty.
I am using multer to do that, here is my code :
My form component :
const WhatsUpForm = ({ className, id, name, placeholder }) => {
const [inputValue, setInputValue] = useState("");
const inputHandler = (e) => {
setInputValue(e.target.value);
};
const submitHandler = async (e) => {
e.preventDefault();
const post = {
author_firstname: JSON.parse(localStorage.getItem("user")).user_firstname,
author_lastname: JSON.parse(localStorage.getItem("user")).user_lastname,
message: inputValue,
date_creation: dayjs().format(),
image_url: ""
};
// POST request
await POST(ENDPOINTS.CREATE_POST, post);
// document.location.reload()
};
return (
<form className={className} onSubmit={submitHandler} method="POST" action="/api/post" enctype="multipart/form-data">
<input className="testt" type="text" id={id} name={name} placeholder={placeholder} required value={inputValue} onChange={inputHandler}/>
<div className="icons_container">
<input type="file" name="image" id="image" className="icons_container__add_file" />
<label for="image">
<FontAwesomeIcon icon={faImages} />
</label>
<button type="submit" className="icons_container__submit">
<FontAwesomeIcon icon={faPaperPlane} />
</button>
</div>
</form>
);
};
My routes and the multer's code :
const multer = require("multer");
const path = require("path");
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "../images");
},
filename: (req, file, callback) => {
console.log("multer");
console.log("file :", file);
callback(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer({ storage: storage });
// Post CRUD
router.get("/", auth, postCtrl.getAllPosts);
router.post("/", auth, upload.single("image"), postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);
router.put("/:id", auth, postCtrl.updatePost);
console.log("multer") is not trigger, and when i look the payload in network tab in my browser, i don't see any images.
And finally, my controller for createPost function :
exports.createPost = (req, res, next) => {
let { body } = req;
delete(req.body.image_url)
body = {
...body,
likes: "",
};
const sql = "INSERT INTO posts SET ?";
db.query(sql, body, (err, result) => {
if (err) {
res.status(404).json({ err });
throw err;
}
res.status(200).json({ msg: "Post added..." });
});
};
For now, i don't want to put the image's URL in my SQL DB, i just want to save the image in my images folders. I have verified the path (../images) and it's coorect.
How do I save the image in my image folder?
I don't see the file data gets sent to server from your POST request.
// object post doesn't have the file data
await POST(ENDPOINTS.CREATE_POST, post);
Consider using FormData
const submitHandler = async (e) => {
e.preventDefault();
const post = new FormData();
// non form data
formData.append("author_firstname", JSON.parse(localStorage.getItem("user")).user_firstname);
...
// form data
formData.append("image", document.getElementById("image").files[0]);
...
// POST request
await POST(ENDPOINTS.CREATE_POST, post);
// document.location.reload()
};

How to send file in form data in Next Js?

I have created an API in Node js for file upload. It is working fine with the postman.
I made a form for uploading Excel files in Next Js. I can able to see selected files in the console.
But I am not able to set the file in formdata. I am getting empty form data in the console.
<div>
<input
class="form-control w-25"
multiple={false}
type="file"
id="ExcelFile"
onChange={uploadFile}
required
></input>
{/* </label> */}
<button
type="button"
// disabled={!selectedImage}
class="btn btn-primary "
>
ADD SOLUTION
</button>
</div>
const uploadFile = ({ target: { files } }) => {
console.log(files[0]);
// let data = new formData();
let FilesData = new FormData();
FilesData.append("excel_file", files[0]);
console.log("Files in multipart");
console.log(FilesData);
// data.append("file", files[0]);
};
https://codesandbox.io/embed/next-js-forked-th22n?fontsize=14&hidenavigation=1&theme=dark
If you try to console.log FormData object, you will just get empty object.Instead you should call the entries method on the FormData object.
for (const pair of FilesData.entries()){
console.log(pair)
}
It will return list of arrays of key-value pairs.
Notice that you can`t see your formData in console.log
If you want to pass data with formData you must use one middleware in your server like this: https://nextjs.org/docs/api-routes/api-middlewares
And i just use one example maybe be usefull:
in your formData:
var FormData = require("form-data");
let data = new FormData()
data.append("urlOrContent", urlOrContent)
and then send your formData in your server side
in your server side:
import middleware from "./middleware/middleware";
import nextConnect from "next-connect";
const handler = nextConnect();
handler.use(middleware);
handler.post(async (req, res) => {
//in formData: req.body.urlOrcontent[0]
try {
const response = await fetch(
req.body?.urlOrContent[0],
);
res.status(200).send({
data: {
message: "Success",
data: response.json(),
},
});
} catch (err) {
let e = {
func: "states.handler",
message: "خطای داخلی سرور رخ داده است!",
error: "Internal Server Error!",
code: 500,
};
res.status(500).json(e);
}
});
export const config = {
api: {
bodyParser: false,
},
};
export default handler;
Here's a little example on a simple form submission in next.js using multer to parse the form data.
Client
This is the client page, containing a super simple HTML form (can work without JS too)
// pages/my-form.ts
export default function Page() {
return (
<div>
<form id="data" method="post" action='/api/on-form-submit' encType="multipart/form-data">
<input name="title" label="Title"/>
<input name="video" label="Video"/>
<button type="submit">Submit</button>
</form>
</div>
);
};
Server
This is the server function that will receive the form submission.
// pages/api/on-form-submit.ts
import multer from "multer";
import { NextApiRequest, NextApiResponse } from "next";
async function parseFormData(
req: NextApiRequest & { files?: any },
res: NextApiResponse
) {
const storage = multer.memoryStorage();
const multerUpload = multer({ storage });
const multerFiles = multerUpload.any();
await new Promise((resolve, reject) => {
multerFiles(req as any, res as any, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
return {
fields: req.body,
files: req.files
}
}
// IMPORTANT: Prevents next from trying to parse the form
export const config = {
api: {
bodyParser: false,
},
};
const Handler: NextApiHandler = async (req, res) => {
const result = await parseFormData(req, res);
console.log(result);
res.status(200).redirect('/success-page');
}
export default Handler;

Why does my DataForm not return as an object that my URL.createObjectURL is supposed to read?

All I am trying to accomplish is to give my users the option to upload images. I decided to use mongoDB as my database which means I must store photos locally and then send them to the DB. As far as I know, I am new. The object created by ImageName and ImageData isn't being passed properly to my axios post request
.post(`http://localhost:5000/api/image/uploadmulter/`, imageFormObj)
.then((data) => {
if (data.data.success) {
alert("Image has been successfully uploaded using multer");
this.setDefaultImage("multerImage");
}
})
Here is my route
const Image = require('../models/imageModel');
const ImageRouter = express.Router();
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb){
cb(null, './uploads/')
},
filename: function(req,file,cb){
cb(null, Date.now() + file.originalname);
}
});
const fileFilter = (req, file, cb) =>{
if(file.mimetype === 'image/jpeg' || file.mimetype ==='image/png'){
cb(null, true);
} else{
//rejects storing file
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits:{
fileSize:1024 *1024 * 5
},
fileFilter: fileFilter
});
// stores image in uploads folder using multers and creates a reference to the file
ImageRouter.route("/upload")
.post(upload.single('imageData'), (req, res, next) => {
console.log(req.body);
const newImage = new Image({
imageName: req.body.imageName,
imageData: req.file.path
});
newImage.save()
.then((result)=>{
console.log(result)
res.status(200).json({
success: true,
document: result
});
})
.catch((err)=> next(err))
});
module.exports = ImageRouter;
here is my model
const Schema = mongoose.Schema;
const ImageSchema = new Schema({
imageName:{
type: String,
default: "none",
required: true
},
imageData: {
type :String,
required: false
}
});
const Image = mongoose.model('Image' , ImageSchema)
module.exports = Image;
Here is my ImageUploader page that calls the function
import axios from 'axios';
import DefaultImg from '../assets/default-img.jpg';
import 'bootstrap/dist/css/bootstrap.min.css';
export default class ImageUploader extends Component {
constructor(props) {
super(props)
this.state = {
multerImage: DefaultImg
}
};
setDefaultImage = (uploadType) => {
if (uploadType === "multer") {
this.setState({multerImage: DefaultImg});
};
};
// function to upload image once it has been captured include multer and
// firebase methods
uploadImage(e, method) {
let imageObj = {};
if (method === "multer") {
let imageFormObj = new FormData();
imageFormObj.append("imageName", "multer-image-" + Date.now());
imageFormObj.append("imageData", e.target.files[0]);
console.log(imageFormObj)
// stores a readable instance of the image being uploaded using multer
this.setState({
multerImage: URL.createObjectURL(e.target.files[0])
});
axios
.post(`http://localhost:5000/api/image/uploadmulter/`, imageFormObj)
.then((data) => {
if (data.data.success) {
alert("Image has been successfully uploaded using multer");
this.setDefaultImage("multerImage");
}
})
.catch((err) => {
alert("Error while uploading image using multer");
this.setDefaultImage("multer");
});
}
};
render() {
return (
<div className="main-container">
<h3 className="main-heading">Image Upload App</h3>
<div className="image-container">
<div className="process">
<h4 className="process__heading">Process: Using Multer</h4>
<p className="process__details">Upload image to a node server, connected to a
MongoDB database, with the help of multer</p>
<input
type="file"
display="block"
className="process__upload-btn"
placeholder="Username"
onChange={(e) => this.uploadImage(e, "multer")
}/>
<img
src={this.state.multerImage}
alt="upload-image"
className="process__image"/>
</div>
</div>
</div>
);
};
};
and finally this is where it's being rendered
// import {EditProfile} from './EditProfile'
import DisplayCats from '../cats/DisplayCats'
// import Button from '#material-ui/core/Button';
import Axios from 'axios';
import ImageUploader from '../ImageUploader';
function ProfilePage(props) {
console.log(props.userInfo)
const user = props.userInfo
console.log(user)
console.log(user._id)
console.log(props.userInfo._id)
let [responseData,
setResponseData] = useState('');
// getLocation = () => {
// navigator
// .geolocation
// .getCurrentPosition(function (position) {
// console.log(position)
// });
// }
const clickHandler = (e) => {
this
.props
.history
.push('/DisplayCats')
}
// const setProfileImage = (event) => {
// Axios
// .post('http://localhost:5000/api/users/updateImage/' + user._id, {
// "_id": user._id,
// "profileImage": event.target.value
// })
// .then(res => {
// setResponseData(res.data)
// console.log(responseData)
// }, function (err) {
// console.log(err)
// })
// }
return (
<div style={{
color: "black"
}}>
<h5>This is {props.userInfo.firstName}'s Profile Page</h5>
<h5>Last name: {props.userInfo.lastName}</h5>
<h5>Age: {props.userInfo.age}</h5>
<h5>Location:{props.userInfo.location}</h5>
<h5>Image:{props.userInfo.profileImage}</h5>
<h5>Biography:{props.userInfo.biography}</h5>
<ImageUploader user={user}/>
{/* <div className="col-md-6 img">
<img
src={responseData.profileImage}
alt="profile image"
className="img-rounded"/>
</div> */}
<div className="row">
<DisplayCats user={user}/>
</div>
{/*
<Button
variant="outlined"
color="primary"
onClick={this.clickHandler}
component={this.EditProfile}
user={this.props.user}>
Edit Info
</Button> */}
</div>
)
}
export default ProfilePage;
I want my image data and and image name to be created into a URL for my other functions to read it. My error comes back as POST /api/image/uploadmulter/ 404 97.290 ms - 163
Perhaps im missing something but from the code you shared, you set your route as:
ImageRouter.route("/upload")
so, your client side code should be posting to: http://localhost:5000/upload
yet, your code does this:
.post(`http://localhost:5000/api/image/uploadmulter/`
You're getting a 404 error, which makes sense since this route hasn't been defined.
On a related note, I'd recommend using something like react-uploady, to manage the uploads on your client-side. It will save you a lot of code and bugs. Especially if you want to show preview or other related functionality (like: progress, cancel, retry, etc.).

Upload image to folder with NextJS api route and isomorphic-unfetch

I'm trying to figure out how I can upload images with NextJS api routes and isomorphic-unfetch. Everything I've seen is utilizing express, but I feel like I should be able to accomplish it with api routes.
So far I have an input of type file that fires an onClick handler:
const handleImage = async (theImg) => {
try {
const res = await fetch("/api/admin", {
method: "POST",
body: theImg,
});
const json = await res.json();
console.log(json);
} catch (error) {
console.log(error);
}
};
return(
<input
onChange={(e) => handleImage(e.target.files[0])}
type="file"
name="uploaded_img"
placeholder="Upload File"
/>
);
but when I try to read the request in the API route, the body appears to be corrupt, and I can't open the resulting file.
api route:
import fs from "fs";
export default async (req, res) => {
try {
const data = fs.writeFile("./uploads/test.jpg", req.body);
//file written successfully
console.log("wrote file");
} catch (err) {
console.error(err);
}
};
the resulting file cannot be opened and contains a bunch of missing characters. I'm probably doing this entirely wrong, but any push in the right direction would be hugely appreciated!

Proxy error: Could not proxy request /users from localhost:3000 to http://localhost:3001/

I'm sending some data from my ReactJS front-end application to my node/express backend, however, whenever I send the data, I get the error message mentioned in the title.
This is my ReactJS code:
class App extends React.Component {
constructor(props) {
super(props);
//states and binding functions
}
fetchData () {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({users}));
}
addUser (event) {
let fileData = new FormData();
fileData.append("file", this.state.filesToBeSent);
axios.post('adduser',
querystring.stringify({
entry: this.state.currname,
passwrd: this.state.currpasswrd,
fileData : fileData
})
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
componentDidMount() {
this.fetchData();
}
render() {
return (
<div className="App">
<form onSubmit={this.addUser} encType="multipart/form-data">
<label>New username:</label>
<input value={this.state.currname} onChange={this.handleChange}></input>
<input value={this.state.currpasswrd} onChange={this.handlePassword} />
<input type="file" name="file" onChange={this.handleFile} />
<button type="submit" >Add</button>
</form>
<h1>Current Users: </h1>
{this.state.users.map((name, n) =>
//map through user-array and display names
)}
</ul>
</div>
);
}
}
(Sorry if it's a lot of code, I shortened it as much as possible but I wasn't sure which parts would be relevant to the question).
Here is how I receive the data in node and how I save parts of it to my db:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
},
filename: (req, file, cb) => {
const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, newFilename);
},
})
const upload = multer({ storage });
router.post("/", upload.single("file"), (req, res) => {
res.send(req.file + " and exit.");
var newUser = new Todo();
newUser.username = req.body.entry;
newUser.passwrd = req.body.passwrd;
newUser.save(function (err) {
if(err)
res.send(err);
res.send('User added successfully!');
});
});
This is where it gets weird. The application works perfectly, until I insert upload.single("file"), however, I couldn't seem to figure out why. I didn't have any problems when I just had text inputs, even when I created the FormData() etc. it still worked fine until I implemented that.
I tried looking it up and to implement answers posted on here, however, nothing seems to help.
On the screen I get the following error message: Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0
When I check the terminal I receive the error message mentioned in the title. I tried removing the content-headers (not sure what that would do, but the tutorial I was following to implement the file upload did not use content-headers, that's why I tried to remove them.
Does anyone know how to fix this error?
Edit: The error message in the terminal also contains ECONNRESET. I followed the link in the terminal https://nodejs.org/api/errors.html#errors_common_system_errors but I'm still not sure how I can fix that.
I suggest you to append all fields to FormData object, and do not convert the submitted data to json string:
let fileData = new FormData();
fileData.append("entry", this.state.currname);
fileData.append("passwrd", this.state.currpasswrd);
fileData.append("file", this.state.filesToBeSent);
axios.post('adduser', fileData)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Resources