1

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!

1 Answer 1

1

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. :)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! This really helps and makes the whole process much simpler. I see here that you've put a comment for success code, what would an example of that be? I can tell that you're doing the POSTing further down in the code and right now I've just got the word 'success' printing to the console as an indicator of where I am in my code. Again, I'm sorry if this is another really stupid question, but how does the post url work here without an action? I think that's what ultimately doesn't make sense to me.
Example of success code? I am using flux architecture. It helps me to broadcast that I have successfully posted image so I update my react component state. how does the post url work here without an action? didn't get your question, try to explain it more please. There's no such thing as a stupid question :)
From my understanding of how POST works, the url needs to be the same as the action on the html form. I tried setting my url to just be '/', as I don't want to redirect anywhere and risk screwing up the image display, but the site doesn't like it. What am I missing?
No. You can post to any url with any data using xhr requests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.