AWS S3 - Image cannot be displayed because it contains errors - node.js

I am currently building a signup form with React, Redux, JavaScript, Node, Adonisjs. I'm attempting to upload profile images to my AWS s3 Bucket. At the moment I've got it so the file is appearing in the bucket. However when I try to click on the link provided by AWS s3 i get the following error. AWS ERROR IMAGE.
I have set my permissions to public and I have provided the correct credential keys. I'm stuck on how to solve this so any help would be greatly appreciated. Please see code below.
Below is my AWS Controller:
"use strict";
require("dotenv").config();
const aws = require("aws-sdk");
const fs = require("fs");
const Helpers = use("Helpers");
const Drive = use("Drive");
class awsController {
async upload({ request, response }) {
aws.config.update({
region: "ap-southeast-2", // AWS region
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECERT
});
const S3_BUCKET = process.env.S3_BUCKET;
const s3Bucket = new aws.S3({
region: "ap-southeast-2",
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECERT,
Bucket: process.env.S3_BUCKET
}); // Create a new instance of S3
const fileName = request.all().body.fileName;
console.log(fileName);
const fileType = request.all().body.fileType;
const params = {
Bucket: S3_BUCKET,
Key: fileName,
ContentType: fileType,
ACL: "public-read"
};
s3Bucket.putObject(params, function(err, data) {
if (err) {
response.send(err);
}
console.log(data);
const returnData = {
signedRequest: data,
url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
};
console.log(returnData);
response.send("Success");
});
}
}
module.exports = awsController;
** Below handles uploading of file **
import React, { Component } from "react";
import axiosAPI from "./../resorterAPI";
import axios from "axios";
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
success: false,
url: ""
};
}
handleChange = event => {};
handleUpload = event => {
let uploadedFile = this.uploadInput.files[0];
// Splits name of file
let fileParts = this.uploadInput.files[0].name.split(".");
let fileName = fileParts[0];
let fileType = fileParts[1];
let fullFileName = uploadedFile.name;
console.log("preparing upload");
axiosAPI
.post("/s3Upload", {
body: {
fileName:
Math.round(Math.random() * 1000 * 300000).toString() +
"_" +
uploadedFile.name,
fileType: fileType
}
})
.then(response => {
console.log("Success");
});
};
render() {
return (
<div>
<center>
<input
onChange={this.handleChange}
ref={ref => {
this.uploadInput = ref;
}}
type="file"
/>
<br />
<button onClick={this.handleUpload}> Upload </button>
</center>
</div>
);
}
}
export default ImageUpload;
**Below is where the image upload service is called **
import React from "react";
// Redux
import { Field, reduxForm } from "redux-form";
import { connect } from "react-redux";
import { getCountry } from "./../../redux/actions/getCountryAction.js";
import Store from "./../../redux/store.js";
// Services
import axiosAPI from "./../../api/resorterAPI";
import ImageUpload from "./../../api/services/ImageUpload";
// Calls a js file with all area codes matched to countries.
import phoneCodes from "./../../materials/PhoneCodes.json";
// Component Input
import {
renderField,
renderSelectField,
renderFileUploadField
} from "./../FormField/FormField.js";
// CSS
import styles from "./signupForm.module.css";
import classNames from "classnames";
function validate(values) {
let errors = {};
if (!values.specialisations) {
errors.firstName = "Required";
}
if (!values.resort) {
errors.lastName = "Required";
}
if (!values.yearsOfExperience) {
errors.email = "Required";
} else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = "Invalid Email";
}
if (!values.spokenLanguages) {
errors.password = "Required";
}
if (values.sport !== values.confirmPassword) {
errors.confirmPassword = "Passwords don't match";
}
return errors;
}
class SignupFormStepTwo extends React.Component {
constructor(props) {
super(props);
this.state = {
countries: [],
selectedCountry: [],
dialCodes: []
};
}
// Below gets the countries from axios call made in redux actions
async componentDidMount() {
const countries = await getCountry();
// The below maps through the json file and gets all the dial codes
const codes = phoneCodes.phoneCode.map(code => {
return code.dial_code;
});
return this.setState({ countries: countries, dialCodes: codes });
}
// Handles when someone changes the select fields
handleChange = event => {
const selectedCountry = event.target.value;
return this.setState({ selectedCountry: selectedCountry });
};
// uploadFile = (values, url = "") => {
// axiosAPI.post("/displayImageUpload", { ...values, imageURL: url}).then(response => {
// console.log("Success");
// })
// }
render() {
return (
<div>
<form onSubmit={this.props.handleSubmit}>
<div className={styles.signupContainer}>
<div className={styles.signupInputContainer}>
{/* <Field
name="displayImage"
component={renderFileUploadField}
type="text"
label="Display Image"
/> */}
<ImageUpload />
<div
className={classNames({
[styles.bioField]: true,
[styles.signupInputContainer]: true
})}
>
<Field
name="bio"
component={renderField}
type="text"
label="Bio"
placeholder="Introduce yourself - Where you're from, what your hobbies are, etc..."
/>
</div>
</div>
{/* Renders the select field */}
<div className={styles.signupInputContainer}>
<Field
name="specialisations"
component={renderSelectField}
type="select"
label="Specialisations"
placeholder="Specialisations"
options={this.state.countries}
onChange={this.handleChange}
multiple={false}
/>
<Field
name="resort"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Resort"
placeholder="Select the resorts you can work at"
/>
<Field
name="yearsOfExperience"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Years of Experience"
/>
<Field
name="spokenLanguages"
component={renderSelectField}
options={this.state.dialCodes}
type="select"
label="Spoken Languages"
/>
</div>
</div>
<div className={styles.signupButtonContainer}>
<button className={styles.signupButton} type="submit">
{" "}
Submit{" "}
</button>
</div>
</form>
</div>
);
}
}
// destroyOnUnmount - saves it in state
SignupFormStepTwo = reduxForm({
form: "signupStageTwo",
destroyOnUnmount: false,
validate
})(SignupFormStepTwo);
const mapStateToProps = state => {
return {
form: state.form
};
};
export default SignupFormStepTwo;

UPDATE: Solved the error thanks to Jarmod, I was actually not separating the file extension from the file name so it was uploading image.png.png.

Related

Process is not defined reference error in blockchain project

I am trying to run my react app but process is not defined is coming up all the time. I am trying to connect with my smart contract using web3.js. My app.jsx file is,
import { useEffect, useState } from "react";
import Web3 from "web3";
import detectEthereumProvider from "#metamask/detect-provider";
import { loadContract } from "./utils/load-contract";
// m,dKK#;fl99
const App = () => {
const [web3Api, setWeb3Api] = useState({
provider: null,
web3: null,
contract: null,
});
const [account, setAccount] = useState(null);
useEffect(() => {
const loadProvider = async () => {
// console.log(window.web3);
// console.log(window.ethereum);
// let provider = null;
// if (window.ethereum) {
// provider = window.ethereum;
// } else if (window.web3) {
// provider = window.web3.currentProvider;
// } else if (!process.env.production) {
// provider = new Web3("http://127.0.0.1:7545");
// }
// try {
// await provider.enable();
// } catch (error) {
// console.log("error", error);
// }
const provider = await detectEthereumProvider();
const contract = await loadContract("Founder", provider);
console.log(contract);
// console.log(provider);
// console.log(prov)
if (provider) {
console.log("Ethereum successfully detected!");
provider.request({ method: "eth_requestAccounts" });
setWeb3Api({
web3: new Web3(provider),
provider,
contract,
});
} else {
console.error("Please install MetaMask!", error);
}
};
loadProvider();
}, []);
useEffect(() => {
const getAccount = async () => {
const acc = await web3Api.web3.eth.getAccounts();
setAccount(acc);
};
web3Api.web3 && getAccount();
}, [web3Api.web3]);
// console.log(web3Api.web3);
// console.log(account);
return (
<>
<div className="card text-center">
<div className="card-header">Funding</div>
<div className="card-body">
<h5 className="card-title">Balance: 20 ETH </h5>
<p className="card-text">
Account : {account ? account : "Not connected"}
</p>
{/*<button
type="button"
className="btn btn-success"
//connect to matamask
onClick={async () => {
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
console.log(accounts);
}}
> */}
{/* <button className="btn btn-success">Connect to metamask</button> */}
<button type="button" className="btn btn-success">
Transfer
</button>
<button type="button" className="btn btn-primary">
Withdraw
</button>
</div>
<div className="card-footer text-muted">Code Eater</div>
</div>
</>
);
};
export default App;
My load-contract file is,
import contract from "#truffle/contract";
export const loadContract = async (name, provider) => {
const res = await fetch(`/contracts/${name}.json`);
const Artifact = await res.json();
const _contract = contract(Artifact);
_contract.setProvider(provider);
const deployedContract = await _contract.deployed();
return deployedContract;
};
Now every time I run this app this error is kept coming,
Uncaught ReferenceError: process is not defined
at node_modules/util/util.js (util.js:109:1)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at node_modules/#truffle/contract-schema/index.js (index.js:3:12)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at node_modules/#truffle/contract/index.js (index.js:1:16)
at __require2 (chunk-S5KM4IGW.js?v=0672b092:18:50)
at index.js:15:18
Now why process is not defined is showing? What did i do wrong?
Now how to fix that. I am using node version 18.12.1 And i don't know how to solve this error. I can't find any good solution for this.

TypeError: _fire__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a function

I've created a login page to my app using firebase authentication. then i've a contact/personal info form which takes images and files as input and uploads them to firebase storage. but i'm facing this issue. This is my first project using react and firebase - would appreciate some simple explanation.
here is my fire.js file
import firebase from 'firebase';
import "firebase/auth";
import "firebase/storage";
if (!firebase.apps.length) {
var fire,storage = firebase.initializeApp({
// my credentials //
});
}else {
fire = firebase.app();
storage = firebase.storage(); // if already initialized, use that one
}
//const fire = firebase.initializeApp(firebaseConfig);
export default {storage,fire};
and here is the page in which I'm trying to add a contact document and then add images to firebase storage:
import React, { useState } from "react";
import { render } from "react-dom";
import { storage } from "./firebase";
import fire from './fire';
const AddRecord = () => {
const [image, setImage] = useState(null);
const [url, setUrl] = useState("");
const [progress, setProgress] = useState(0);
const handleChange = e => {
if (e.target.files[0]) {
setImage(e.target.files[0]);
}
};
const handleUpload = () => {
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
snapshot => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
error => {
console.log(error);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
setUrl(url);
});
}
);
};
console.log("image: ", image);
return (
<div>
<progress value={progress} max="100" />
<br />
<br />
<input type="file" onChange={handleChange} />
<button onClick={handleUpload}>Upload</button>
<br />
{url}
<br />
<img src={url || "http://via.placeholder.com/300"} alt="firebase-image" />
</div>
);
};
export default AddRecord;

_id is missing after doing actions

i'm currently creating my first MERN App, and everything is going well, until something happened, and i'm going my try to explain because i need help !
What i'm doing is a facebook clone, where you can post something, you can delete your post and you can update your post, the logic is simple, i call dispatch to pass the data to the actions, the actions pass the data to the backend, and the backend return something to me and it saves in my store, because i'm using redux
The problem is that, when i have 2 post, and i want to delete a post, or maybe i want to edit it, the other post dissapears, it's like it loses its id and then loses the information, then i can't do anything but reaload the page, and it happens always
this is how it looks like, everything fine
Then, after trying to edit a post, the second one lost its information, and in the console, it says that Warning: Each child in a list should have a unique "key" prop, and i already gave each post the key={_id}, but the post lost it and i don't know how
Here's the code
Posts.js
import React, { useState } from "react";
import "./Posts.css";
import moment from "moment";
// Icons
import { BiDotsVertical, BiLike } from "react-icons/bi";
import { MdDeleteSweep } from "react-icons/md";
import { AiFillLike } from "react-icons/ai";
import { GrClose } from "react-icons/gr";
// Calling actions
import { deletePost, } from "../actions/posts.js";
// Gettin The Data From Redux
import { useSelector, useDispatch } from "react-redux";
const Posts = ({ setCurrentId }) => {
const [animation, setAnimation] = useState(false);
const [modal, setModal] = useState(false);
const [modalPost, setModalPost] = useState({});
// Getting The Posts
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
// Showing And Hiding Modal Window
const ModalWindow = post => {
setModalPost(post);
setModal(true);
};
// Liking the post
// const Like = id => {
// dispatch(giveLike(id));
// setAnimation(!animation);
// };
if (!posts.length) {
return <div>Loading</div>;
} else {
return (
<div className="Posts">
{/* // Modal window for better look to the post */}
{/* {modal && (
<div className="modalWindow">
<div className="container">
<div className="container-image">
<img src={modalPost.image} alt="" />
</div>
<div className="information">
<div className="container-information">
<div className="data-header">
<h2>
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(modalPost.createdAt).fromNow()}
</span>
</h2>
<span className="data-icon" onClick={() => setModal(false)}>
<GrClose />
</span>
</div>
<div className="message">
<h2>{modalPost.title}</h2>
<p>{modalPost.message}</p>
</div>
</div>
</div>
</div>
</div>
)} */}
{/* */}
{posts.map(post => {
const { _id, title, message, image, createdAt, likes } = post;
return (
<div className="Posts-container" key={_id}>
<div className="Fit">
<div className="Fit-stuff">
<h2 className="Fit-stuff_title">
User <br />{" "}
<span style={{ fontWeight: "400" }}>
{moment(createdAt).fromNow()}
</span>
</h2>
<a
className="Fit-stuff_edit"
href="#form"
onClick={() => setCurrentId(_id)}
>
<BiDotsVertical />
</a>
</div>
<div className="Fit-data">
<h2 className="Fit-data_title">{title}</h2>
<p className="Fit-data_message">{message}</p>
{image ? (
<div className="Fit-img">
<img
onClick={() => ModalWindow(post)}
src={image}
alt=""
/>
</div>
) : (
<div></div>
)}
</div>
<div className="Fit-shit">
<span>
{animation ? (
<AiFillLike className="fullLightBlue" />
) : (
<BiLike />
)}
{likes}
</span>
<span onClick={() => dispatch(deletePost(_id))}>
<MdDeleteSweep />
</span>
</div>
</div>
</div>
);
})}
</div>
);
}
};
export default Posts;
The form where i call update and create Post
import React, { useState, useEffect } from "react";
import Filebase from "react-file-base64";
// For the actions
import { useDispatch, useSelector } from "react-redux";
import { createPost, updatePost } from "../actions/posts.js";
import {
Wrapper,
FormContainer,
Data,
DataInput,
SecondDataInput,
FormContainerImg,
FormContainerButtons,
Buttons
} from "./FormStyled.js";
const Form = ({ currentId, setCurrentId }) => {
const [formData, setFormData] = useState({
title: "",
message: "",
image: ""
});
const specificPost = useSelector(state =>
currentId ? state.posts.find(p => p._id === currentId) : null
);
// Sending The Data And Editing The data
const dispatch = useDispatch();
useEffect(() => {
if (specificPost) setFormData(specificPost);
}, [specificPost]);
// Clear Inputs
const clear = () => {
setCurrentId(0);
setFormData({ title: "", message: "", image: "" });
};
const handleSubmit = async e => {
e.preventDefault();
if (currentId === 0) {
dispatch(createPost(formData));
clear();
} else {
dispatch(updatePost(currentId, formData));
clear();
}
};
return (
<Wrapper>
<FormContainer onSubmit={handleSubmit}>
<Data>
<DataInput
name="title"
maxLength="50"
placeholder="Title"
type="text"
value={formData.title}
onChange={e => setFormData({ ...formData, title: e.target.value })}
/>
<SecondDataInput
name="message"
placeholder="Message"
maxLength="300"
value={formData.message}
required
onChange={e =>
setFormData({ ...formData, message: e.target.value })
}
/>
<FormContainerImg>
<Filebase
required
type="file"
multiple={false}
onDone={({ base64 }) =>
setFormData({ ...formData, image: base64 })
}
/>
</FormContainerImg>
<FormContainerButtons>
<Buttons type="submit" create>
{specificPost ? "Edit" : "Create"}
</Buttons>
<Buttons onClick={clear} clear>
Clear
</Buttons>
</FormContainerButtons>
</Data>
</FormContainer>
</Wrapper>
);
};
export default Form;
My actions
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
import * as api from "../api/posts.js";
export const getPosts = () => async dispatch => {
try {
const { data } = await api.getPosts();
dispatch({ type: GETPOSTS, payload: data });
} catch (error) {
console.log(error);
}
};
export const createPost = newPost => async dispatch => {
try {
const { data } = await api.createPost(newPost);
dispatch({ type: CREATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const updatePost = (id, updatePost) => async dispatch => {
try {
const { data } = await api.updatePost(id, updatePost);
dispatch({ type: UPDATEPOST, payload: data });
} catch (error) {
console.log(error);
}
};
export const deletePost = id => async dispatch => {
try {
await api.deletePost(id);
dispatch({ type: DELETEPOST, payload: id });
} catch (error) {
console.log(error);
}
};
Redux Part
import {
GETPOSTS,
CREATEPOST,
DELETEPOST,
UPDATEPOST,
LIKEPOST
} from "../actionTypes/posts.js";
const postData = (posts = [], action) => {
switch (action.type) {
case GETPOSTS:
return action.payload;
case CREATEPOST:
return [...posts, action.payload];
case UPDATEPOST:
return posts.map(post =>
action.payload._id === post._id ? action.payload : posts
);
case DELETEPOST:
return posts.filter(post => post._id !== action.payload);
default:
return posts;
}
};
export default postData;
My controllers in the backend
import mongoose from "mongoose";
import infoPost from "../models/posts.js";
// Getting All The Posts
export const getPosts = async (req, res) => {
try {
const Posts = await infoPost.find();
res.status(200).json(Posts);
} catch (error) {
res.status(404).json({ message: error.message });
console.log(error);
}
};
// Creating A Post
export const createPost = async (req, res) => {
const { title, message, image } = req.body;
const newPost = new infoPost({ title, message, image });
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
console.log(error);
}
};
// Update A Post
export const updatePost = async (req, res) => {
const { id } = req.params;
const { title, message, image } = req.body;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No Post With Id Of ${id}`);
const updatedPost = { title, message, image, _id: id };
await infoPost.findByIdAndUpdate(id, updatedPost, { new: true });
res.json(updatedPost);
};
// Deleting A Post
export const deletePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res
.status(404)
.send(`We Couldnt Found The Post With Id Of ${id} To Delete`);
await infoPost.findByIdAndRemove(id);
res.json(`Post With Id Of ${id} Deleted Succesfully`);
};
// Liking A Post
export const likePost = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).send(`No post with id: ${id}`);
const post = await infoPost.findById(id);
const updatedPost = await infoPost.findByIdAndUpdate(
id,
{ likeCount: post.likeCount + 1 },
{ new: true }
);
res.json(updatedPost);
};
Even though i've been trying to solve this problem for nearly 3.5 hours, i think that the problem might be in my Posts.js part, if you can help me, you're the greatest !

3D model renderer component not loading file

I'm working on a feature for a web app I'm developing that consists in a .obj model viewer. The thing is that I don't really know how to work with the three.js library so I decided to go with a dependency to do the trick, I'm using this one. Basically what I'm doing is to get the content of the file in the redux state which is initially obtained by a backend request, so, I ultimately use the state variable and pass it a component prop to the <OBJModel /> component, but I get this error when trying to load:
https://pasteboard.co/Jtdkigq.png
https://pasteboard.co/JtdkPoRk.png
This is the front-end code:
import React from 'react';
import { OBJModel } from 'react-3d-viewer';
import { connect } from 'react-redux';
import { getModel } from './../../actions';
import golem from './../../Stone.obj';
class ModelViewer extends React.Component {
componentDidMount() {
document.querySelector('#upload-modal').style.display = 'flex';
let id = '';
let slashCounter = 0;
for (let i = 0; i < window.location.pathname.length; i++) {
if (slashCounter === 2) {
id = id + window.location.pathname[i];
}
if (window.location.pathname[i] === '/') {
slashCounter++;
}
}
this.props.getModel(id);
}
render() {
if (this.props.model.previewModel)
console.log(this.props.model.previewModel);
return (
<div style={{ display: 'flex', justifyContent: 'center' }}>
{!this.props.model.previewModel ? null : (
<OBJModel
height="500"
width="500"
position={{ x: undefined, y: -5, z: undefined }}
src={this.props.model.previewModel}
/>
)}
<div id="upload-modal" className="upload-modal">
<div className="upload-modal-content">
<p className="upload-modal-header">
<i
className="exclamation circle icon"
style={{ color: 'gray' }}
/>
Loading model...
</p>
<div
className="ui indicating progress active progress-indicator"
id="upload-bar-indicator"
>
<div className="bar" id="upload-bar">
<div className="progress" id="modal-upload-progress"></div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { model: state.model };
};
export default connect(mapStateToProps, { getModel })(ModelViewer);
This is the action function that makes the request to the backend:
export const getModel = (id) => {
return async (dispatch) => {
const config = {
onDownloadProgress: function (progressEvent) {
let percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
document.querySelector(
'#modal-upload-progress'
).innerHTML = `${percentCompleted}%`;
document.querySelector(
'#upload-bar'
).style.width = `${percentCompleted}%`;
document
.querySelector('#upload-bar-indicator')
.setAttribute('data-percent', `${percentCompleted}`);
},
};
const response = await axios.get(
`https://hushpuppys-3d-hub-api.herokuapp.com/api/v1/modelfiles/${id}.obj`,
config
);
document.querySelector('#upload-modal').style.display = 'none';
dispatch({ type: 'GET_MODEL', payload: response.data.data });
};
};
This is the controller that downloads the file from the Cloud Storage where im storing the files:
exports.fileDownloaderController = async (req, res) => {
try {
const fileName = req.params.id;
const config = {
headers: { Authorization: credentials.authorizationToken },
};
await axios
.get(
`${credentials.downloadUrl}/file/hushpuppys-3d-hub-storage/${fileName}`,
config
)
.then(function (response) {
console.log(response.data);
res.status(200).json({
status: 'success',
data: response.data,
});
})
.catch(function (err) {
console.log(err); // an error occurred
});
} catch (err) {
console.log(err);
res.status(404).json({
status: 'fail',
message: err.message,
});
}
};
And this is how the downloaded files look like when they are downloaded from the server, and logged in the console:
https://pasteboard.co/JtdpMCi.png

send an image file from react to node.js

I am currently working upload a profile picture and save the picture at aws s3 bucket.
When I send an image file through Postman, there were no error just works fine. I was able to upload a file to multer and aws s3.
However, when I tried to upload a picture through react front-end, It doesn't show any file. req.file is undefined.
I tried to figure this problem for weeks but still have no clue. I tried data.append profilepic[0] but it still didn't work.
React Code
clickSubmit = event => {
event.preventDefault()
const {profilepic, fname, lname, password, passwordconfirm} = this.state
const data = new FormData();
console.log(profilepic[0]);
// data.append('profilepic', profilepic[0], profilepic[0].name);
const user ={
fname,
lname,
password,
passwordconfirm,
profilepic
};
console.log(user);
this.signup(user).then(data => {
console.log(data)
if(data.error) {
this.setState({error: data.error});
}
else{
this.setState({
fname:"",
lname: "",
password: "",
error: "",
open: true,
passwordconfirm: "",
// profilepic: [],
});
}
});
};
onDrop(picture) {
this.setState({
profilepic: picture,
});
console.log(this.state.profilepic);
}
signup = user => {
return fetch("http://localhost:3003/auth/mtregister",{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:3003"
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
inspect console shows file information
console from front-end
mtregister node.js
const db = require('../../dbconfig.js');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const {promisify} = require('util');
const nodemailer = require('nodemailer');
const multer = require('multer');
const fs = require('fs');
const aws = require('aws-sdk');
aws.config.update({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY,
region: 'us-east-1',
});
//Creating a new instance of S3:
const s3= new aws.S3();
// Set up Multer Storage
const storage = multer.diskStorage({
destination: "../../public/images",
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage });
/*mentor register*/
exports.mtregister = [upload.single('profilepic'), async(req,res)=>
{
console.log(req.body);
console.log(req.file);
....
}
the output of console.log(req.body);console.log(req.file); is empty [ {} ] and undefined.
console.log results
I recommend use Axios to make http request from React. The Docummentation is good.
Example from: https://www.nicesnippets.com/blog/react-js-file-upload-example-with-axios
import React from 'react'
import axios from 'axios';
class FileUpload extends React.Component{
constructor(){
super();
this.state = {
selectedFile:'',
}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState({
selectedFile: event.target.files[0],
})
}
submit(){
const data = new FormData()
data.append('file', this.state.selectedFile)
console.warn(this.state.selectedFile);
let url = "http://localhost:8000/upload.php";
axios.post(url, data, { // receive two parameter endpoint url ,form data
})
.then(res => { // then print response status
console.warn(res);
})
}
render(){
return(
<div>
<div className="row">
<div className="col-md-6 offset-md-3">
<br /><br />
<h3 className="text-white">React File Upload - Nicesnippets.com</h3>
<br />
<div className="form-row">
<div className="form-group col-md-6">
<label className="text-white">Select File :</label>
<input type="file" className="form-control" name="upload_file" onChange={this.handleInputChange} />
</div>
</div>
<div className="form-row">
<div className="col-md-6">
<button type="submit" className="btn btn-dark" onClick={()=>this.submit()}>Save</button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default FileUpload;

Resources