0

I am using ReactJS to create a simple sendMail app. And the problem is I do not receive req.file in my server (ExpressJS).

myForm.js

<form className="content-container mailing-form" encType='multipart/form-data'>
            <h1>Let's see if it works</h1>
            <div>
                <label>Mail: </label>
                <input type="text" value={this.state.email} onChange={this.handleChangeToMail} style={{ width: '50%' }} />
            </div>
            <div>
                <label>Subject: </label>
                <input type="text" value={this.state.subject} onChange={this.handleChangeSubject} style={{ width: '50%' }} />
            </div>
            <div>
                <textarea
                    id="test"
                    name="test-mailing"
                    onChange={this.handleChangeFeedback}
                    placeholder="Post some lorem ipsum here"
                    required
                    value={this.state.feedback}
                    style={{ width: '100%', height: '150px' }}
                />
            </div>
            <div> //Here is my input file
                <label>File: </label>
                <input
                    type="file"
                    onChange={this.handleChangeFile}
                    name="myFile"
                />
                <img src="" id="preview" alt="Image preview..."></img>
            </div>
            <input type="button" value="Submit" onClick={this.handleSubmit} />
        </form>

handleChangeFile

handleChangeFile = e => {
    e.preventDefault();

    let fReader = new FileReader();
    let file = '';

    fReader.readAsDataURL(e.target.files[0]);
    fReader.onloadend = (event) => {
        document.getElementById('preview').src = event.target.result;
        file = event.target.result;
        this.setState(() => ({ file }));
        console.log(this.state.file);
    }

}

handleSubmit

handleSubmit = e => {
    let formData = new FormData();

    formData.append('name', this.state.name);
    formData.append('email', this.state.email);
    formData.append('feedback', this.state.feedback);
    formData.append('subject', this.state.subject);
    formData.append('file', this.state.file);

    const config = {
        headers: {
            "Content-Type": "multipart/form-data",
            "Accept": "application/json",
            "type": "formData"
        }
    }

    const url = "http://localhost:8081/send";

    axios
        .post(
            url,
            formData,
            config
        )
        .then(res => console.log(res.data))
        .catch(err => console.log('Error: ', err));
}

Server.js

const nodemailer = require('nodemailer'); 
const express = require('express'); 
const bodyParser = require('body-parser'); 
const cors = require('cors'); 
var multer = require('multer');

const app = express(); 
const port = 8081;

app.use(cors()); 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next(); });

app.get('/', (req, res) => res.send('......!'));


const storage = multer.diskStorage({
    destination: './uploads',
    filename: function (req, file, cb) {
        cb(null, file.fieldname + Date.now());
    } })

const uploads = multer({
    storage: storage 
}).single('myFile');

app.post('/send', uploads, (req, res) => {
    if (req.file) {
        res.send('Uploaded !');
    } else {
        res.send('Fail !!');
    }
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

And I keep receive "Fail !!" message on my form.

I have tried to add any solution I can find. I know it can be some mess in there, sorry for that :') !

Quang Huy
  • 13
  • 1
  • 4

2 Answers2

1

I solved my problem, thanks to this thread : Convert Data URI to File then append to FormData

I add a function to convert file from weird base64 string to Blob type before send it to server. Then my server can receive req.file !!

Quang Huy
  • 13
  • 1
  • 4
0

1.make your uploads folder as static folder

app.use(express.static('uploads'));

2.change your destination like below

 destination : function( req , file , cb ){  
    cb(null,'./uploads');
 },
  1. append your file as myFile in frontend

formData.append('myFile', this.state.file);

Community
  • 1
  • 1
Prakash Karena
  • 2,525
  • 1
  • 7
  • 16
  • I change it and the error is the same. Still get empty req.file. It appears in req.body.file in Base64 type and it just a string, not structure I saw from another solutions and I don't know what to do with it to convert it to images that upload at local files. – Quang Huy Jan 15 '20 at 11:55