How to submit multipart/form-data from react to express? - node.js

I'm trying to submit a form with an Image & Name of Category. But in my ExpressJS (backend) I'm unable to fetch the data. In express I'm using express-fileupload package. Below is my code, please help me to come out from this problem.
Front End (React - CategoryForm.js)
import axios from "axios";
import React, { Component } from "react";
class CategoryForm extends Component {
constructor(props) {
super(props);
this.state = { name: '', file: '', fileName: '' };
this.onChange = this.onChange.bind(this);
this.onChangeImageHandler = this.onChangeImageHandler.bind(this);
this.onCreate = this.onCreate.bind(this);
}
/** Methods */
onChange = e => this.setState({ [e.target.name]: e.target.value });
onChangeImageHandler = e => this.setState({ fileName: e.target.files[0].name, file: e.target.files[0] });
onCreate = async e => {
e.preventDefault();
e.stopPropagation();
const formData = new FormData();
formData.append('name', this.state.name);
formData.append('file', this.state.file);
const url = 'http://localhost:4000/api/v2/categories';
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkZTc3MDM0NTgxM2QyN2NmZDExMWE3ZSIsImVtYWlsIjoiaGFyc2hhQHNrcmVlbS5pbyIsImlhdCI6MTU3NTQ0ODc1OSwiZXhwIjoxNTc2MzEyNzU5fQ.7wxCmPhkzb0aaB4q9PBKmHAj1Klw1NQmp1nBI3NsRRI';
axios({
method: 'POST',
url: url,
headers: {
Authorization: `Bearer ${token}`,
ContentType: 'multipart/form-data'
},
body: formData
})
.then(res => this.setState({ name: '', file: '', fileName: '' }))
.catch(err => console.log('Error - ', err));
}
/** Rendering the Template */
render() {
const { name, fileName } = this.state;
return (
<form onSubmit={this.onCreate}>
<input type="text" name="name" value={name} onChange={this.onChange} placeholder="New Category Name" />
<input type="file" name="file" onChange={this.onChangeImageHandler} />
<button type="submit">Add Category</button>
</form>
)
}
}
export default CategoryForm;
Back End (ExpressJS : server.js)
const express = require("express");
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/api/v2/categories',
(req, res, next) => { console.log(req.body); },
require("./categoryRoute"));
In req.body I'm getting { }. Please tell me How can send Image with Text data to express.
Note : If I'm passing only data (Not Image) from react, let say data: {name: 'Shivam'} then I'm getting it in backend.

React:
convert your media file to base64 string.
Express Js:
In express convert base64 to image(img,pdf,xlxs,etc...)
var base64Data = req.body.file_data // base64 string
var file_name='123.png';
var file_dir = "assets/client_folios/"
var fs = require("fs");
if (!fs.existsSync('assets/')){
fs.mkdirSync('assets/');
}
if (!fs.existsSync(file_dir)){
fs.mkdirSync(file_dir);
}
var file_path="assets/client_folios/"+file_name
var file_path="assets/client_folios/"+file_name
fs.writeFile(file_path, base64Data, 'base64',async function(err) {
}

Related

why my req.files always null while req.body have the file :upload file with express-fileupload/reactjs

i need ur help i can't find the mistake :
I m trying to upload a file in my code using express-fileupload but in nodemon the req.files are always null: files: null but I find that my file attribute pass to req.body like : body: { file: '[object File]' }
i try testing my URL with RESTer and it's work the file upload but didn t work with my react input i try all the last 4days lot of things but i still didn t find where is my mistake is it in formData?? plaise help me
there is my code for frontend react:
import Message from './Message';
import Progress from './Progress';
import axios from 'axios';
const FileUpload = () => {
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose File');
const onChange = e => {
console.log(e.target.files[0].name)
setFile([e.target.files[0]]);
setFilename(e.target.files[0].name);
};
const onSubmit = async e => {
const formData = new FormData();
formData.append("file", file);
if(!formData){
console.log("empty");}
try {
const res = await axios.post('http://localhost:5001/up', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log("file read");
console.log(res)
const { fileName, filePath } = res.data;
} catch (err) {
console.log(err)
}
};
return (
<Fragment>
<form onSubmit={onSubmit} enctype='multipart/form-data'>
<div className='custom-file mb-4'>
<input
type='file'
enctype='multipart/form-data'
className='custom-file-input'
id='customFile'
onChange={onChange}
/>
<label className='custom-file-label' htmlFor='customFile'>
{filename}
</label>
</div>
<input
type='submit'
value='Upload'
className='btn btn-primary btn-block mt-4'
/>
</form>
</Fragment>
);
};
export default FileUpload;
and there is the backend :
import cors from "cors"
import nez_topographie from "./api/controllers/nez_topographie.route.js"
import fileUpload from "express-fileupload"
import multer from "multer"
import bodyParser from "body-parser"
import morgan from "morgan"
const app = express()
app.use(fileUpload({
createParentPath: true
}))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan("dev"))
app.use("/nez_topographie", nez_topographie)
app.post('/up', async (req, res) => {
try {
console.log(req)
if(!req.files) {
console.log("no")
res.send({
status: false,
message: 'No file uploaded'
});
} else {
//Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.file;
//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./' + avatar.name);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
console.log(err)
res.status(500).send(err);
}
});
export default app
I just ran into this same issue. I had to add a filename to my FormData instance on the front end.
const formData = new FormData();
formData.append("file", file, "myfile.txt");
If you want you can also pass the original file name like so
formData.append("file", file, file.name);

req.file is showing undefined in console

I am trying to upload a video on youtube from my web app but I am getting an error in sending a file to my backend it is showing the req.file as undefined in req.body it is showing videoFile: "Undefined" and all other values I can see but I am not able to get the file from my react app to backend .
Input.jsx
import axios from "axios";
import React, { useState } from "react";
// import Axios from "axios";
function Input() {
const [form, setForm] = useState({
title: "",
description: "",
file: null,
});
function handleChange(event) {
const InputValue =
event.target.name === "file" ? event.target.file : event.target.value;
setForm({
...form,
[event.target.name]: InputValue,
});
}
function handleSubmit(event) {
event.preventDefault();
console.log({ form });
const headers = {
"content-type": "multipart/form-data",
};
const videoData = new FormData();
videoData.append("videoFile", form.file);
videoData.append("title", form.title);
videoData.append("description", form.description);
axios
.post("http://localhost:3001/upload", videoData, { headers })
.then((res) => {
console.log(res.data);
})
.catch((err) => console.log(err));
}
return (
<div className="form">
<h1>
<i className="fab fa-youtube"></i> Upload video
</h1>
<form onSubmit={handleSubmit} method="POST" enctype="multipart/form-data">
<div>
<input
className="title"
type="text"
placeholder="Title"
name="title"
autoComplete="off"
onChange={handleChange}
/>
</div>
<div>
<textarea
typeof="text"
placeholder="description"
name="description"
autoComplete="off"
onChange={handleChange}
/>
</div>
<div>
<input
type="file"
accept="video/mp4,video/x-m4v,video/*"
placeholder="Add"
name="file"
onChange={handleChange}
/>
</div>
<button className="btn btn-light" type="submit">
Upload Video
</button>
</form>
</div>
);
}
export default Input;
it is node.js part
App.js (backend)
const express = require("express");
const multer = require("multer");
const youtube = require("youtube-api");
const open = require("open");
const cors = require("cors");
const fs = require("fs");
const credentials = require("./client_secret_1013548512515-lti2tpl88m8qqkum1hh095cnevtdi3lu.apps.googleusercontent.com.json");
const app = express();
const bodyParser = require("body-parser");
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
const storage = multer.diskStorage({
destination: "./",
filename: (req, file, cb) => {
const newFileName = `${Date.now()}-${file.originalname}`;
cb(null, newFileName);
},
});
const uploadVideoFile = multer({
storage: storage,
}).single("videoFile");
app.post("/upload", uploadVideoFile, (req, res) => {
console.log(req.body);
console.log(req.file); //it is showing undefined
if (req.file) { //getting error in this part
const filename = req.file.filename;
const { title, description } = req.body;
open(
oAuth.generateAuthUrl({
access_type: "offline",
scope: "https://www.googleapis.com/auth/youtube.upload",
state: JSON.stringify({
filename,
title,
description,
}),
})
);
}
});
app.get("/oauth2callback", (req, res) => {
res.redirect("http://localhost:3000/success");
const { filename, title, description } = JSON.parse(req.query.state);
oAuth.getToken(req.query.code, (err, tokens) => {
if (err) {
console.log(err);
return;
}
oAuth.setCredentials(tokens);
youtube.videos.insert(
{
resource: {
snippet: { title, description },
status: { privacyStatus: "private" },
},
part: "snippet,status",
media: {
body: fs.createReadStream(filename),
},
},
(err, data) => {
console.log("Done");
process.exit();
}
);
});
});
const oAuth = youtube.authenticate({
type: "oauth",
client_id: credentials.web.client_id,
client_secret: credentials.web.client_secret,
redirect_url: credentials.web.redirect_uris[0],
});
PORT = 3001;
app.listen(PORT, () => {
console.log("app is listening on port 3001");
});
Please make the following changes in the Input.jsx file.
// 1. Inside the handleChange() function
const InputValue = event.target.name === "file" ? event.target.files : event.target.value;
// 2. Inside the handleSubmit() function
videoData.append("videoFile", form.file[0], form.file[0].name);
This should output the file object inside req.file.

Fetch /POST request to Server: Empty array when receiving multipart/form-data;

Im trying to upload an image (ReactJs) to my server (NodeJs+ Express+ multerJs) to digital Ocean.
Im using a POST Request with multipart/form-data;
I get a succesfull message from multerJs but I can see in the log on the server that the files: [] has an empty array. And that Digital Ocean didnt add any file of course.
When i do the same Post request with the form without handling the submission of the form ,everything is working and the Files array is not empty.the code above is working :
<form method="post" enctype="multipart/form-data" action="http://localhost:3004/upload_image_test_4" > </form>
Client-Side React.js :
export default class Select_size extends React.Component {
on_form_submit = (e) => {
e.preventDefault();
const fileInput = this.state.file;
const formData = new FormData();
formData.append('file', fileInput);
const options = {
method: 'POST',
body: formData,
headers: {
'Access-Control-Allow-Origin': '*',
Accept: 'application/json',
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
}
};
var url =
this.state.action_link +
'?url=' +
this.state.id_user +
'/' +
this.state.id_draft +
'&name=' +
this.state.name_file;
fetch(url, options);
};
onChange = (e) => {
this.setState({ file: e.target.files[0] });
};
constructor(props) {
super(props);
this.state = {
files: [],
};
this.onChange = this.onChange.bind(this);
}
render() {
return (
<form onSubmit={this.on_form_submit} enctype="multipart/form-data">
<input type="file" name="myImage" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)}
}
Server-side (Node.js/ ExpressJs/Multer/Digital Ocean) :
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const aws = require('aws-sdk');
const spacesEndpoint = new aws.Endpoint('fra1.digitaloceanspaces.com');
const s3 = new aws.S3({
endpoint: spacesEndpoint,
accessKeyId: 'myID',
secretAccessKey: 'MySecretKey'
});
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'bucketName',
acl: 'public-read',
key: function(request, file, cb) {
cb(null, urlBucket + name_image);
}
})
}).array('upload', 1);
router.post('/upload_image_test_4', function(request, response, next) {
upload(request, response, function(error) {
console.log(request, 'the request');
if (error) {
console.log(error);
return response.json(error, 'error');
}
console.log('File uploaded successfully.');
return response.json('success its uploaded to digital ocean');
});
});
module.exports = router;
If anyone can help me with that ! (I already 'googled' insanely,,,)
Thanks !!
//EDIT I found a solution to my own question... on the github page dedicated to a bug related to Next.js :
The file was not send to the request for some reasons.
I used axios in this way and its now working :
React-js :
sendFile = (e) => {
const data = new FormData();
const file = e.target.files[0];
data.append('avatar', file);
axios
.post('http://localhost:3004/upload_test_stack_2', data)
.then(console.log)
.catch(console.error);
}
The server side (nodeJs) :
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'My Bucket',
acl: 'public-read',
key: function(request, file, cb) {
cb(null, file.originalname);
}
})
});
router.post('/upload_test_stack_2', upload.single('avatar'), (req, res)
=> {
console.log(req.file, 'The file appears here');
return res.sendStatus(200);
});
Files from input are not an array but FileArray, try [...e.target.files][0]
Related to Event Pooling in React and async behavior of setState.
Modify onChange handler:
Method 1:
Put the file to variable and set it in setState.
onChange = (e) => {
const uploadFile = e.target.files[0] ;
this.setState({ file: uploadFile });
};
Method 2 with event.persist():
onChange = (e) => {
e.persist();
this.setState({ file: e.target.files[0] });
};

ReactNative : variable for FormData() being logged as undefined in ReactNative application when i make an http request with a file

i have been trying to make a post request from my react native app on an android emulator but the object that i am sending in the body of the request is being vvalued as undefined,been trying alot to solve this issue but no success. Please help me
here is the code to my form in the app known as "API.js" its named so just for testing the API endpoints
import React, { Component } from "react";
import {
Text,
TextInput,
View,
TouchableHighlight,
StyleSheet,
Button,
FormData
} from "react-native";
import Permissions from "react-native-permissions";
import ImagePicker from "react-native-image-crop-picker";
import axios from "axios";
var styles = StyleSheet.create({});
var msg = "Select Image";
var data;
export default class API extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
price: "",
size: "",
description: "",
image: "",
popularity: ""
};
}
FormDataFunc() {
let form = new FormData();
form.append("name", this.state.name);
form.append("price", this.state.price);
form.append("size", this.state.size);
form.append("description", this.state.description);
form.append("image", this.state.image);
form.append("popularity", this.state.popularity);
return form;
return form;
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
Submit() {
axios({
method: "post",
url: "http://192.168.0.102:3000/products",
data: this.FormDataFunc,
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: this.FormDataFunc
})
.then(() => {
console.log("DONE!");
this.props.navigation.navigate("offersScreen");
})
.catch(err => {
console.log(err);
console.log(this.FormDataFunc);
});
}
componentDidMount() {
Permissions.check("photo").then(response => {
// Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
console.log(response);
});
}
render() {
const image = () => {
ImagePicker.openPicker({
multiple: false,
includeBase64: true
}).then(images => {
console.log(images);
this.setState({
images: { data: `\`${images.mime}\`;base64,\`${images.data}\`` }
});
console.log(this.state.images);
msg = "Selected";
});
};
return (
<View>
<TextInput placeholder="Name" name="name" />
<TextInput placeholder="Price" name="price" />
<TextInput placeholder="Size" name="size" />
<TextInput placeholder="Description" name="description" />
<TouchableHighlight onPress={image} name="image">
<Text>{msg}</Text>
</TouchableHighlight>
<TextInput placeholder="Popularity" name="popularity" />
<TouchableHighlight title="Submit" onPress={this.Submit}>
<Text>Send</Text>
</TouchableHighlight>
</View>
);
}
}
here is the code to my backend route "product.js" which recieves the request(node.js and express)
const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const path = require("path");
const cloudinary = require("cloudinary");
const mongoose = require("mongoose");
//Product Model
const product = require("../models/product").product;
router.use(bodyParser.json());
//GET route
router.get("/", (req, res) => {
product.find().then(product => res.json(product));
});
// POST route
cloudinary.config({
cloud_name: "cloud222",
api_key: "783935981748815",
api_secret: "uY47vBS1rI2x5jvFtnXQIjMMqU0"
});
router.post("/", (req, res) => {
//MISC//
let imageUrl;
console.log("starting");
//MISC//
//CLOUDINARY UPLOAD
cloudinary.v2.uploader.upload(req.body.image, (error, result) => {
if (error) {
console.log(error);
console.log(`${req.body.image}`);
} else {
imageUrl = result.secure_url;
//MONGO UPLOAD
var productv = {
name: req.body.name,
price: req.body.price,
size: req.body.size,
description: req.body.description,
image: imageUrl,
popularity: req.body.popularity
};
const productvar = new product(productv);
productvar
.save()
.then(product => console.log(product))
.then(product => res.json(product))
.catch(err => console.log(err));
}
});
//END//
});
module.exports = router;
the data is being logged as undefined and therefore the request doesnt get a response
I think the problem is that you have created a FormData and wanted to post it, but the headers you added is "application/json". You should change it:
headers: {
'content-type': 'multipart/form-data',
'Accept':'multipart/form-data',
},
Hope it works for you.
Problem solved
Had to use onChangeText = instead of onChange as onChange does not return a string

Upload image file from React front end to Node/Express/Mongoose/MongoDB back end (not working)

I’ve spent most of a day looking into this and trying to make it work. This is an app with a React/Redux front end, and a Node/Express/Mongoose/MongoDB back end.
I currently have a Topics system where an authorized user can follow/unfollow topics, and an admin can Add/Remove topics.
I want to be able to upload an image file when submitting a new topic, and I want to use Cloudinary to store the image and then save the images path to the DB with the topic name.
The problem I am having is that I am unable to receive the uploaded file on the back end from the front end. I end up receiving an empty object, despite tons of research and trial/error. I haven’t finished setting up Cloudinary file upload, but I need to receive the file on the back end before even worrying about that.
SERVER SIDE
index.js:
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const app = express();
const router = require("./router");
const mongoose = require("mongoose");
const cors = require("cors");
const fileUpload = require("express-fileupload");
const config = require("./config");
const multer = require("multer");
const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");
app.use(fileUpload());
//file storage setup
cloudinary.config({
cloud_name: "niksauce",
api_key: config.cloudinaryAPIKey,
api_secret: config.cloudinaryAPISecret
});
const storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: "images",
allowedFormats: ["jpg", "png"],
transformation: [{ width: 500, height: 500, crop: "limit" }] //optional, from a demo
});
const parser = multer({ storage: storage });
//DB setup
mongoose.Promise = global.Promise;
mongoose.connect(
`mongodb://path/to/mlab`,
{ useNewUrlParser: true }
);
mongoose.connection
.once("open", () => console.log("Connected to MongoLab instance."))
.on("error", error => console.log("Error connecting to MongoLab:", error));
//App setup
app.use(morgan("combined"));
app.use(bodyParser.json({ type: "*/*" }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
router(app, parser);
//Server setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log("server listening on port: ", port);
TopicController/CreateTopic
exports.createTopic = function(req, res, next) {
console.log("REQUEST: ", req.body); //{ name: 'Topic with Image', image: {} }
console.log("IMAGE FILE MAYBE? ", req.file); //undefined
console.log("IMAGE FILES MAYBE? ", req.files); //undefined
const topic = new Topic(req.body);
if (req.file) {
topic.image.url = req.file.url;
topic.image.id = req.file.publid_id;
} else {
console.log("NO FILE UPLOADED");
}
topic.save().then(result => {
res.status(201).send(topic);
});
};
router.js
module.exports = function(app, parser) {
//User
app.post("/signin", requireSignin, Authentication.signin);
app.post("/signup", Authentication.signup);
//Topic
app.get("/topics", Topic.fetchTopics);
app.post("/topics/newTopic", parser.single("image"), Topic.createTopic);
app.post("/topics/removeTopic", Topic.removeTopic);
app.post("/topics/followTopic", Topic.followTopic);
app.post("/topics/unfollowTopic", Topic.unfollowTopic);
};
CLIENT SIDE
Topics.js:
import React, { Component } from "react";
import { connect } from "react-redux";
import { Loader, Grid, Button, Icon, Form } from "semantic-ui-react";
import {
fetchTopics,
followTopic,
unfollowTopic,
createTopic,
removeTopic
} from "../actions";
import requireAuth from "./hoc/requireAuth";
import Background1 from "../assets/images/summer.jpg";
import Background2 from "../assets/images/winter.jpg";
const compare = (arr1, arr2) => {
let inBoth = [];
arr1.forEach(e1 =>
arr2.forEach(e2 => {
if (e1 === e2) {
inBoth.push(e1);
}
})
);
return inBoth;
};
class Topics extends Component {
constructor(props) {
super(props);
this.props.fetchTopics();
this.state = {
newTopic: "",
selectedFile: null,
error: ""
};
}
onFollowClick = topicId => {
const { id } = this.props.user;
this.props.followTopic(id, topicId);
};
onUnfollowClick = topicId => {
const { id } = this.props.user;
this.props.unfollowTopic(id, topicId);
};
handleSelectedFile = e => {
console.log(e.target.files[0]);
this.setState({
selectedFile: e.target.files[0]
});
};
createTopicSubmit = e => {
e.preventDefault();
const { newTopic, selectedFile } = this.state;
this.props.createTopic(newTopic.trim(), selectedFile);
this.setState({
newTopic: "",
selectedFile: null
});
};
removeTopicSubmit = topicId => {
this.props.removeTopic(topicId);
};
renderTopics = () => {
const { topics, user } = this.props;
const followedTopics =
topics &&
user &&
compare(topics.map(topic => topic._id), user.followedTopics);
console.log(topics);
return topics.map((topic, i) => {
return (
<Grid.Column className="topic-container" key={topic._id}>
<div
className="topic-image"
style={{
background:
i % 2 === 0 ? `url(${Background1})` : `url(${Background2})`,
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
backgroundSize: "cover"
}}
/>
<p className="topic-name">{topic.name}</p>
<div className="topic-follow-btn">
{followedTopics.includes(topic._id) ? (
<Button
icon
color="olive"
onClick={() => this.onUnfollowClick(topic._id)}
>
Unfollow
<Icon color="red" name="heart" />
</Button>
) : (
<Button
icon
color="teal"
onClick={() => this.onFollowClick(topic._id)}
>
Follow
<Icon color="red" name="heart outline" />
</Button>
)}
{/* Should put a warning safety catch on initial click, as to not accidentally delete an important topic */}
{user.isAdmin ? (
<Button
icon
color="red"
onClick={() => this.removeTopicSubmit(topic._id)}
>
<Icon color="black" name="trash" />
</Button>
) : null}
</div>
</Grid.Column>
);
});
};
render() {
const { loading, user } = this.props;
if (loading) {
return (
<Loader active inline="centered">
Loading
</Loader>
);
}
return (
<div>
<h1>Topics</h1>
{user && user.isAdmin ? (
<div>
<h3>Create a New Topic</h3>
<Form
onSubmit={this.createTopicSubmit}
encType="multipart/form-data"
>
<Form.Field>
<input
value={this.state.newTopic}
onChange={e => this.setState({ newTopic: e.target.value })}
placeholder="Create New Topic"
/>
</Form.Field>
<Form.Field>
<label>Upload an Image</label>
<input
type="file"
name="image"
onChange={this.handleSelectedFile}
/>
</Form.Field>
<Button type="submit">Create Topic</Button>
</Form>
</div>
) : null}
<Grid centered>{this.renderTopics()}</Grid>
</div>
);
}
}
const mapStateToProps = state => {
const { loading, topics } = state.topics;
const { user } = state.auth;
return { loading, topics, user };
};
export default requireAuth(
connect(
mapStateToProps,
{ fetchTopics, followTopic, unfollowTopic, createTopic, removeTopic }
)(Topics)
);
TopicActions/createTopic:
export const createTopic = (topicName, imageFile) => {
console.log("IMAGE IN ACTIONS: ", imageFile); //this is still here
// const data = new FormData();
// data.append("image", imageFile);
// data.append("name", topicName);
const data = {
image: imageFile,
name: topicName
};
console.log("DATA TO SEND: ", data); //still shows image file
return dispatch => {
// const config = { headers: { "Content-Type": "multipart/form-data" } };
// ^ this fixes nothing, only makes the problem worse
axios.post(CREATE_NEW_TOPIC, data).then(res => {
dispatch({
type: CREATE_TOPIC,
payload: res.data
});
});
};
};
When I send it like this, I receive the following on the back end:
(these are server console.logs)
REQUEST: { image: {}, name: 'NEW TOPIC' }
IMAGE FILE MAYBE? undefined
IMAGE FILES MAYBE? undefined
NO FILE UPLOADED
If I go the new FormData() route, FormData is an empty object, and I get this server error:
POST http://localhost:3090/topics/newTopic net::ERR_EMPTY_RESPONSE
export const createTopic = (topicName, imageFile) => {
console.log("IMAGE IN ACTIONS: ", imageFile);
const data = new FormData();
data.append("image", imageFile);
data.append("name", topicName);
// const data = {
// image: imageFile,
// name: topicName
// };
console.log("DATA TO SEND: ", data); // shows FormData {} (empty object, nothing in it)
return dispatch => {
// const config = { headers: { "Content-Type": "multipart/form-data" } };
// ^ this fixes nothing, only makes the problem worse
axios.post(CREATE_NEW_TOPIC, data).then(res => {
dispatch({
type: CREATE_TOPIC,
payload: res.data
});
});
};
};
Solution was to switch to using Firebase instead, and deal with image upload on the React client (this was attempted with cloudinary but with no success). The resulting download url can be saved to the database with the topic name (which is all I wanted from cloudinary) and now it is displaying the correct images along with the topics.

Resources