A.S.J
A.S.J

Reputation: 637

Multer upload multiple files from different inputs

I'm rather new to multer/node/express/mongoose/... and I'm currently trying to upload multiple files from different inputs that have the same name (I generate the inputs using reactjs).

Here's my React front-end:

onSubmit = (e) => {

    e.preventDefault();

    const {imges} = this.state;
    let formData = new FormData();

    formData.append('imges', imges);

    axios.post('newuser',
        formData)
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
}

handleFileChange(inputid, file) {
    const data = [...this.state.data];
    this.setState({
        imges: this.state.imges.concat(file)
    }, () => console.log(this.state.imges));
}

render() {
    return(
        <form onSubmit={this.onSubmit} encType="multipart/form-data">
            <Imageinput onhandleChange={this.handleFileChange}/>
        </form>
    )
}

I didn't add in how I generate the fields because I felt that it wasn't relevant to the question, however, I would like to note that the user can generate however many of these file-inputs with the name-attribute "picture" as he wants.

Here's my node.js backend:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "./uploads/");
    },

    filename: (req, file, cb) => {
        const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
        cb(null, newFilename);
    },
})

const upload = multer({ storage: storage });
router.post("/", upload.array("picture"), (req, res) => {
    console.log(req.files + " and exit");
    res.end();
});

module.exports = router;

I also tried using upload.any() but it didn't work and I also read that there can be security hazards with using that. I'm a little confused here, all questions/answers I've seen up until now simply use req.files and they receive an array of their files or at least something, but for me the terminal simply prints out and exit so I'm assuming there is a mistake within my code. I also tried setting "picture[]" as the name of my inputs, since, in php that indicated an array of files (I know php is not node.js, but I wanted to try out as much as possible before asking here).

To sum up my question: I would like to retrieve the filedata from my files from different inputs, which have the same name, using multer. It is not working, therefore I would like to ask if anyone knows what I did wrong in this case and how I can fix it.

(Edit: This is probably a little of topic but it seems to me that this question is too "small" to be asked as its own question. In my form I also have a few text inputs. Before using multer I stored the data gathered from each of my components (Imageinput) in its own array in the state like so:

 data : [{data1: value, imgsrc: value}, {data1: value, imgsrc: value}, ... ]

Can send the images as a part of this array using multer? ).

Upvotes: 0

Views: 4950

Answers (1)

udaykumar vangari
udaykumar vangari

Reputation: 91

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './client/uploads/')
    },
      filename: function (req, file, cb) {
        cb(null, Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1]) //Appending extension
    }
});

const Upload = multer({storage: storage}).any();

router.post('/', function (req, res) {
    Upload(req, res, function (err, filedata) {
        if (err) {
            res.json({error_code: 1, err_desc: err});

        } else {
            functionName(req.files, function (result) {
                            res.json(result);
            })
        }
       })
});

Upvotes: 2

Related Questions