Skip to content

Instantly share code, notes, and snippets.

@1travelintexan
Created April 11, 2022 13:37
Show Gist options
  • Save 1travelintexan/9f91aca2c0aab500dbd1f8604ba8680a to your computer and use it in GitHub Desktop.
Save 1travelintexan/9f91aca2c0aab500dbd1f8604ba8680a to your computer and use it in GitHub Desktop.
// the following 3 packages are needed in order for cloudinary to run
const cloudinary = require("cloudinary").v2; // for verification
const multer = require("multer"); // middleware for handling data, which is primarily used for uploading files
const { CloudinaryStorage } = require("multer-storage-cloudinary"); // to access cloudinary storage
// your three cloudinary keys will be passed here from your .env file
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_API_SECRET,
});
const storage = new CloudinaryStorage({
cloudinary,
folder: "JoshIsCool", // The name of the folder in cloudinary . You can name this whatever you want
allowedFormats: ["jpg", "png"],
// params: { resource_type: 'raw' }, => add this is in case you want to upload other type of files, not just images
filename: function (req, res, cb) {
cb(null, res.originalname); // The file on cloudinary will have the same name as the original file name
},
});
module.exports = multer({ storage });
// POST route for saving a user image in the database
// This route has the image upload example
router.post("/upload", fileUploader.single("imageUrl"), (req, res) => {
let userId = req.session.user._id;
let newImage = req.file.path;
console.log("the image is here!", req.file, userId);
User.findByIdAndUpdate(userId, { imageUrl: newImage })
.then((updatedUser) => {
console.log("here is the Updated User", updatedUser);
res.status(200).json(updatedUser);
})
.catch((error) =>
console.log(`Error while creating a new movie: ${error}`)
);
});
unction Profile({ currentUser, setUser }: IProps) {
const navigate = useNavigate();
function handleUserImage(event: any) {
event.preventDefault();
let image = event.target.imageUrl.files[0];
let imageFormData = new FormData();
imageFormData.append("imageUrl", image);
async function sendImage() {
let updatedUser = await axios.post(`${API_URL}/upload`, imageFormData, {
withCredentials: true,
});
console.log("saved", updatedUser.data);
let _id = updatedUser.data._id;
let username = updatedUser.data.username;
let imageUrl = updatedUser.data.imageUrl;
setUser({
_id,
username,
imageUrl,
});
}
sendImage();
}
return (
<div>
<div>
{currentUser.imageUrl ? (
<img
src={currentUser.imageUrl}
alt="profile pic"
style={{ height: "100px" }}
/>
) : null}
{currentUser ? (
<h1>Welcome {currentUser.username}!</h1>
) : (
<p>Loading</p>
)}
<button onClick={handleLogout}>Logout</button>
</div>
<div>
<h3>Update your User Image:</h3>
<form
onSubmit={handleUserImage}
method="post"
encType="multipart/form-data"
>
<input type="file" accept="image/png, image/jpg" name="imageUrl" />
<button type="submit">Update</button>
</form>
</div>
</div>
);
}
export default Profile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment