How to upload and get image / formData with react native axios and multer - react-native

I try to post images to MongoDB but get status CODE 404,
I have multer and static path '/uploads/' and this directory is on the frontend with some images, I get the array from the server but i dont know how to show them :
i tried in flat list to show them like:
<Image source={require("../../server/uploads/a3.jpg")} />//here its work.
and when i replace to {require("../../server/${item.imageurl}" iI get error
when i console log the require path I get the objects with url->> ../../server/uploads\a1.jpg
see that the / is the opposite side \ , maybe its the problem?
now for upload I tried to :
I getting object(selectedImage) when I choosing file :
"localUri": "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLior-
3698f362-fc81-4a77-8c97-8cd1349ce090/ImagePicker/d4c4b4ec-72e6-4e20-b6eb-4727bc84d93e.jpg",
and my axios post:
if (selectedImage !== null) {
let formData = new FormData();
formData.append("image", selectedImage);
console.log(formData);
try {
const response = await indexApi.post(`/uploads`, formData);
console.log("res", response);
} catch (err) {
console.log("c", err);
}
}
};
the form data that i send look like:
FormData {
"_parts": Array [
Array [
"image",
Object {
"localUri":
"file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FLior-3698f362-fc81-
4a77-8c97-8cd1349ce090/ImagePicker/d4c4b4ec-72e6-4e20-b6eb-4727bc84d93e.jpg",
},
],
],
}
and I get error 404, or 503.....
the backend parts:
image controller:
const Image = require("../models/image");
const _ = require("lodash");
exports.getImages = (req, res) => {
Image.find()
.select("_id image desc")
.then(images => {
res.json({ images });
})
.catch(err => console.log("get images errors", err));
};
//INSERT NEW IMAGE//
exports.uploadImage = (req, res) => {
const image = new Image({
image: req.file.path,
desc: req.body.desc,
});
console.log(image);
console.log(image);
console.log("ss", image);
image.save(err => {
if (err) {
return res.status(400).json({ error: "העלאת תמונה נכשלה" });
}
res.json({ message: "העלאת תמונה עברה בהצלחה" });
});
};
image route:
const express = require("express");
const { getImages, uploadImage } = require("../controllers/image");
const multer = require("multer");
//configure the images
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
console.log("f", file);
cb(null, file.originalname);
},
});
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 55,
},
});
const router = express.Router();
router.get("/images", getImages);
router.post("/images/new", upload.single("image"), uploadImage);
module.exports = router;
so maybe my prolbem go from the route... beacuse i dont understand the that thing that i have one route (uploads) for the images, and another route with get and post method(/images) and for post (/images/new)
Edit. Error Picture for the first part

Try fixing this first:-
a. Your require might not able to read the incoming value from item.imageUrl since you called it inside double quotes (""):-
try using backticks (``):-
<Image source={require(`../../server/${item.imageUrl}`)} />
OR
You could try one of these two ways:-
saving image path in db
in imageUpload method/function:-
//INSERT NEW IMAGE//
exports.uploadImage = (req, res) => {
const image = new Image({
// don't do this
// image: req.file.path,
// instead try do this
image: '/uploads/' + req.file.originalname,
desc: req.body.desc,
});
console.log(image);
console.log(image);
console.log("ss", image);
image.save(err => {
if (err) {
return res.status(400).json({ error: "העלאת תמונה נכשלה" });
}
res.json({ message: "העלאת תמונה עברה בהצלחה" });
});
saving image originalname only in db
in imageUpload method/function:-
//INSERT NEW IMAGE//
exports.uploadImage = (req, res) => {
const image = new Image({
// don't do this
// image: req.file.path,
// instead try do this
image: req.file.originalname,
desc: req.body.desc,
});
console.log(image);
console.log(image);
console.log("ss", image);
image.save(err => {
if (err) {
return res.status(400).json({ error: "העלאת תמונה נכשלה" });
}
res.json({ message: "העלאת תמונה עברה בהצלחה" });
});
in 'view' or front-end:-
<Image source={require(`../../server/uploads/${item.imageUrl}`)} />

Related

How do I make express middleware in class?

I currently use multer middleware like below
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public");
},
filename: function (req, file, cb) {
cb(null, req.params.id + "_" + file.originalname);
},
});
export const multerUploadSingle = (req: Request, res: Response, next: NextFunction) => {
const upload = multer({ storage: storage }).single("file");
upload(req, res, (error: unknown) => {
if (error instanceof multer.MulterError) {
const message = `file upload fail: ${error.message}`;
next(new HttpException(message, HttpStatus.BadRequest));
} else if (error instanceof Error) {
const message = `file upload fail: ${error.message}`;
next(new HttpException(message, HttpStatus.InternalServerError));
} else {
// upload success
next();
}
});
}
and use in router like this
FileRouter.post("/upload/:id", multerUploadSingle, (req, res) => {...});
However, I felt I want to refactor this middleware in class, and rewrote the code like this,
export class Multer {
private readonly storage: multer.StorageEngine;
constructor() {
this.storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public");
},
filename: function (req, file, cb) {
cb(null, req.params.id + "_" + file.originalname);
},
});
}
uploadSingle(req: Request, res: Response, next: NextFunction) {
const upload = multer({ storage: this.storage }).single("file");
upload(req, res, (error: unknown) => {
if (error instanceof multer.MulterError) {
const message = `file upload fail: ${error.message}`;
next(new HttpException(message, HttpStatus.BadRequest));
} else if (error instanceof Error) {
const message = `file upload fail: ${error.message}`;
next(new HttpException(message, HttpStatus.InternalServerError));
} else {
// upload success
next();
}
});
}
}
const multer = new Multer();
FileRouter.post("/upload/:id", multer.uploadSingle, (req, res) => {...});
With my short knowledge, I think both case should have the same result, but the latter case which uses class made middleware doesn't work at all. It's seems method "uploadSingle" is never called, thus multer not uploading the file.
Did I make any mistake with class usage? or is it just express can only use function defined middleware?
Your code should follow the MVC pattern.
You can do stuff like this:
routerFile.js
const upload = require("../../configs/multer");
const postController = require("../../controllers/postController");
const multiUploadEvent = upload.fields([
{ name: "images", maxCount: 2 },
{ name: "video", maxCount: 2 }
]);
router.post("/add-event-post", multiUploadEvent, postController.addEventPost);
module.exports = router;
multer.js
const multer = require('multer');
const multerFilter = (req, file, cb) => {
console.log("Mime type :", file.mimetype.split('/')[0]);
if (file.mimetype.split('/')[0] === 'image' || file.mimetype.split('/')[0] === 'video' || file.mimetype.split('/')[0] === 'audio') {
cb(null, true);
} else {
cb(new Error('Please upload img, audio, or video file only.'), false);
}
};
const storage = multer.memoryStorage();
const upload = multer({
storage: storage,
fileFilter: multerFilter,
limits: {
fileSize: , 50 * 1024 * 1024// 50 Mb
},
});
module.exports = upload;
postController.js
const addEventPost = async (request, response) => {
try {
let { title, ..... } = request.body;
const images = request.files.images;
const video = request.files.video;
console.log(title);
console.log(images);
console.log(videos);
//upload to services likes aws and save to database
.
.
.
return response
.status(200)
.json({
message: "Event post added successfully"
});
} catch (error) {
console.log(error);
response.status(500).json({
error: "Something went wrong",
});
}
}

express crashes if req.file is undefined

when making a post request to an express api without an attached file in the request, the api crashes and provides the TypeError: Cannot read properties of undefined (reading 'filename') error. However i would like to make it so the api does not crash when a post request is made without an attached image. any ideas ?
express code :
const storage = multer.diskStorage({
destination: (req, res, cb) => {
cb(null, dir)
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname)
}
})
const upload = multer({
storage: storage
})
router.get('/', async (req, res) => {
try {
const members = await Member.find();
res.json(members);
} catch (err) {
res.status(500).json({ message: err.message });
}
})
router.get('/:id', getMember, async (req, res) => {
res.json(res.member)
})
router.post('/', upload.single('image'), async (req, res) =>{
const member = new Member({
name: req.body.name,
occupation: req.body.occupation,
bio: req.body.bio,
join: req.body.join,
image: req.file.filename
})
try {
const newMember = await member.save()
res.status(201).json(newMember)
} catch (err) {
res.status(400).json({ message: err.message });
}
})
nextjs code to actually send the file:
const submitHandler = (e) => {
e.preventDefault()
const formDatas = new FormData()
formDatas.append('name', name)
formDatas.append('occupation', occupation)
formDatas.append('bio', paragraph)
formDatas.append('join', date)
formDatas.append('image', img)
console.log(formDatas)
axios
.post(api + '/members', formDatas)
.then(res => console.log(res))
.catch(err => console.log(err))
}
Error occurred because you're trying to access object of undefined variable req.file;
You can make changes according to your need
1 If you don't want to accept request without any file
router.post('/', upload.single('image'), async (req, res) => {
if (!req.file) { //or you can check if(req.file===undefiend)
return res.status(400).json({ message: 'Please attach a file' });
}
const member = new Member({
name: req.body.name,
occupation: req.body.occupation,
bio: req.body.bio,
join: req.body.join,
image: req.file.filename
})
try {
const newMember = await member.save()
res.status(201).json(newMember)
} catch (err) {
res.status(400).json({ message: err.message });
}
})
2 If you want to store null/empty string (in case of no file upload)
router.post('/', upload.single('image'), async (req, res) => {
const member = new Member({
name: req.body.name,
occupation: req.body.occupation,
bio: req.body.bio,
join: req.body.join,
image: req.file!==undefined ? req.file.filename : null
})
try {
const newMember = await member.save()
res.status(201).json(newMember)
} catch (err) {
res.status(400).json({ message: err.message });
}
})
Change as shown below
const member = new Member({
name: req.body.name,
occupation: req.body.occupation,
bio: req.body.bio,
join: req.body.join,
image: req.file.filename ? req.file.filename : ""
})
This should stop crashing but until I see the whole code wont know how you are handling error

Using aws-sdk to upload to DigitalOceans

I'm using aws-sdk to upload images to DigitalOceans bucket. On localhost it works 100% but production seems like the function goes on without an error but the file does not upload to the bucket.
I cannot figure out what is going on and can't think of a way to debug this. tried aswell executing the POST request with Postman multipart/form-data + adding file to the body of the request and it is the same for localhost, working, and production is not.
my api endpoint:
import AWS from 'aws-sdk'
import formidable from "formidable"
import fs from 'fs'
const s3Client = new AWS.S3({
endpoint: process.env.DO_SPACES_URL,
region: 'fra1',
credentials: {
accessKeyId: process.env.DO_SPACES_KEY,
secretAccessKey: process.env.DO_SPACES_SECRET
}
})
export const config = {
api: {
bodyParser: false
}
}
export default async function uploadFile(req, res) {
const { method } = req
const form = formidable()
const now = new Date()
const fileGenericName = `${now.getTime()}`
const allowedFileTypes = ['jpg', 'jpeg', 'png', 'webp']
switch (method) {
case "POST":
try {
form.parse(req, async (err, fields, files) => {
const fileType = files.file?.originalFilename?.split('.').pop().toLowerCase()
if (!files.file) {
return res.status(400).json({
status: 400,
message: 'no files'
})
}
if (allowedFileTypes.indexOf(fileType) === -1) {
return res.status(400).json({
message: 'bad file type'
})
}
const fileName = `${fileGenericName}.${fileType}`
try {
s3Client.putObject({
Bucket: process.env.DO_SPACES_BUCKET,
Key: `${fileName}`,
Body: fs.createReadStream(files.file.filepath),
ACL: "public-read"
}, (err, data) => {
console.log(err)
console.log(data)
})
const url = `${process.env.FILE_URL}/${fileName}`
return res.status(200).json({ url })
} catch (error) {
console.log(error)
throw new Error('Error Occured While Uploading File')
}
});
return res.status(200)
} catch (error) {
console.log(error)
return res.status(500).end()
}
default:
return res.status(405).end('Method is not allowed')
}
}

Cloudinary\Error: Missing required parameter - file - Express and Postman

first time trying to upload images to Cloudinary and I have come across an issue when using Express via Postman.
Using form-data on setting 'file' to upload an image to Cloudinary
As of now, when I try to access the req.body I get an empty object, so I guess that has to do with why cloudinary.uploader.upload cannot read the file passed as its first param, since its req.body.file, as shown in the code below.
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET
})
exports.upload = async (req, res) => {
try{
console.log(req.body);
const result = await cloudinary.uploader.upload(req.body.file, {
public_id: `${Date.now()}`,
resource_type: "auto"
})
return res.json({
public_id: result.public_id,
url: result.secure_url
})
}catch(err){
console.log(err)
}
}
The error message I get:
{
message: 'Missing required parameter - file',
name: 'Error',
http_code: 400
}
Any suggestions to solve this issue?
I solved it! I was not able to pass the form-data as req.body to the server, so I had to try and access it through req.files, but was not able to with that either, so I searched a bit and found a middleware 'express-fileupload', and that did the trick. I just added it in my app.js and used
const fileupload = require('express-fileupload');
app.use(fileupload({useTempFiles: true}))
So now I can access my req.files.
exports.upload = async (req, res) => {
const file = req.files.image
try{
console.log(file);
const result = await cloudinary.uploader.upload(file.tempFilePath, {
public_id: `${Date.now()}`,
resource_type: "auto"
})
res.json({
public_id: result.public_id,
url: result.secure_url
})
}catch(err){
console.log("Error", err)
return res.status(400).json({error: err})
}
}
The response I get is:
{
name: 'some-image.png',
data: <Buffer >,
size: 99770,
encoding: '7bit',
tempFilePath: ' **C:\\filepath\some-image.png** ',
truncated: false,
mimetype: 'image/png',
md5: 'b5f612a571442bf604952fd12c47c1bf',
mv: [Function: mv]
}
POST /cloudinary/upload-images 200 1617.944 ms - 119
And it is uploaded successfully to my Cloudinary.
const result = await cloudinary.uploader.upload(req.file, {
public_id: ${Date.now()},
resource_type: "auto"
})
and add file from form data and type should be File
Solved!
This is how i am setting the FormData
let myTestForm = new FormData();
myTestForm.set("name", name);
myTestForm.set("email", email);
myTestForm.set("Avatar", Avatar);
myTestForm.set("password", password);
This is how i am using the FormData
const config = {
headers: {
"Content-type": "multipart/form-data",
},
};
const { data } = await axios.post(`/api/v1/register`, userData, { config });
please don't pass it this way { userData} , had struggled for with this :/
This is how i am uploading image
const myCloud = await cloudinary.v2.uploader.upload(req.body.Avatar, {
folder: "Avatars",
width: 150,
crop: "scale",
public_id: `${Date.now()}`,
resource_type: "auto",
});
PS : in my case i had to upload only 1 image. Have not passed any parameter in app.js file
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());

Uploading photo from react native(expo) camera to aws s3 after resized by lambda

Progress until now
I have created an app.
captured image from app has a object like this
`
{
"height": 4000,
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fimage-upload-4ceaf845-d42a-4a1d-b1be-5a3f9cfd10ba/Camera/e3d441b6-2664-4c30-a093-35f7f0f09488.jpg",
"width": 3000,
}
`
I have made an end point in api gateway and api gateway connects to a lambda and i'm sending above data to my backend as `
axios
.post(uploadEndPoint, capturedImage, {
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
`
i get captured data in my lambda
first i'm trying to save in s3 with out resizing like this if this works then i will go for resizing.
`
import Responses from '../utils/responses';
import * as fileType from 'file-type';
import { v4 as uuid } from 'uuid';
import * as AWS from 'aws-sdk';
const s3 = new AWS.S3();
const allowedMimes = ['image/jpeg', 'image/png', 'image/jpg'];
export const handler = async (event) => {
console.log('event>>', JSON.parse(event.body));
try {
const body = JSON.parse(event.body);
if (!body) {
return Responses._400({ message: 'incorrect body on request' });
}
let imageData = body;
console.log('imageData>>', imageData);
const buffer = Buffer.from(imageData, 'base64');
console.log('buffer>>', buffer);
const fileInfo = await fileType.fromBuffer(buffer);
console.log(fileInfo);
const detectedExt = fileInfo.ext;
const detectedMime = fileInfo.mime;
console.log('detectedExt>>', detectedExt);
console.log('detectedMime>>', detectedMime);
if (!allowedMimes.includes(detectedMime)) {
return Responses._400({ message: 'mime is not allowed ' });
}
const name = uuid();
const key = `${name}.${detectedExt}`;
console.log(`writing image to bucket called ${key}`);
await s3
.putObject({
Body: buffer,
Key: key,
ContentType: detectedMime,
Bucket: process.env.imageUploadBucket,
ACL: 'public-read',
})
.promise();
const url = `https://${process.env.imageUploadBucket}.s3-${process.env.region}.amazonaws.com/${key}`;
return Responses._200({
imageURL: url,
});
} catch (error) {
console.log('error', error);
return Responses._400({
message: error.message || 'failed to upload image',
});
}
};
`
fileInfo shows undifined
Things i want
Resize image and upload to s3 by that lambda