DottoraQN
DottoraQN

Reputation: 3

Uploading an image and displaying that image on the page (Node.js, React,js, Express.js)

I need to upload an image to a site and display it in the page after it's uploaded with a caption of the filename under the image. I've searched all over and found lots of tutorials about uploading and displaying on the same page, but I think that I just have a breakdown in my understanding of what goes into requesting info from a server and then displaying it back.

I'm writing my web app in node+react and using express and multer for the file IO. Here is my code:

import React from 'react';
import ReactDOM from 'react-dom';
import Dropzone from 'react-dropzone-component';
import fs from 'fs';
import express from 'express';
import mutler from 'mutler';

var app = express();
var storage;
var upload;

export default class Form extends React.Component {
constructor (props) {
    super(props);
    storage =  multer.diskStorage({
        //file destination
        destination: function (req, file, callback) {
            callback(null, '/uploads/');
        },
        //set the filename
        filename: function (req, file, callback) {
            callback(null, file.originalname);
            this.state = {
                name: file.originalname
            };
        }
    });
    upload = multer({ storage : storage}).single('userImage');
    app.use('/uploads/', express.static(__dirname + '/uploads/'));
}

handleImageUpload () {
    app.post('/', function (req, res) {
        fs.readFile(req.files.userImage.path, function(err, data) {
            console.log('error with ' + data);
        });
        upload(req, res, function (err) {
            if (err) {
                return res.end("Error uploading file.");
            }

            res.writeFile("/uploads/" + origName, new Buffer(req.body.photo, "base64"), function(err) {
                console.log("error writing image");
            });
            res.redirect('/');
        });
    });
}

getName () {
    return this.state.name;
}

render () {
    return (<div>
        <form action="/" method="post" enctype="multipart/form-data">
            <input type="image" name="userImage"/>
            <input type="submit" name="submit" value="submit" onClick={this.handleImageUpload.bind(this)}/>
        </form>
    </div>

    );
}

}

I've tried following multiple tutorials (which is why Dropzone is imported) but I just can't figure this out for what I want to do.

I figured that if I save the filename to state in the constructor, that then I can get it later and display it in another file, which is simply attributing the file's url to an image source in a higher up react file.

My question is this: where have I gone wrong? By my reasoning this should work, but I'm new to file IO with node and what seems to be common knowledge to a lot of people in the tutorials that I've read just isn't clicking with me. Thank you in advance for your help!

Upvotes: 0

Views: 2695

Answers (1)

m.rohail.akram
m.rohail.akram

Reputation: 350

Use following module to select images.
https://www.npmjs.com/package/react-image-uploader

You can then upload image to server using xhr request. Following is the sample code.

var xhr  = new XMLHttpRequest();
xhr.onload = function (e) {
//your success code goes here
}
var formData = new FormData();
xhr.open("POST", url, true);
formData.append('file', fileData);
xhr.send(formData);

I am assuming that you are implementing following requirement.

  1. Allow user to select image.
  2. Upload selected image
  3. Show selected image to user.

What my solution will help

  1. Allow user to select image
  2. Show user what he/she selected.
  3. Upload image to server by available callback(mentioned in tutorial)
  4. Show success or failure.

If you need any help do let me know. :)

Upvotes: 1

Related Questions