0

im trying to make something like google drive, but my own, started with very simple file/image uploading, down here is my Node.js Back-end, and more down there is my Front-end JavaScript/Axios/React/html server, after i upload any file in front end(on website) i get error in Node.js(see down there), in Node.js im using multer to manage receive files

Node.js

const path = require('path');
const express = require("express");
const cors = require("cors");
const https = require('https');
const fs = require('fs');
const MySQL = require('./middleware/database');
const JWT = require('./middleware/verifyJWT');

const multer  = require('multer')

const app = express();

const sslServer = https.createServer(
  {
    key: fs.readFileSync(path.join(__dirname, 'ssl', 'key.pem')),
    cert: fs.readFileSync(path.join(__dirname, 'ssl', 'cert.pem')),
  },
  app
);

app.use(express.json());
app.use(
  cors({
    origin: [process.env.CORS_ORIGIN],
    methods: ["GET", "POST"],
    credentials: true,
  })
);

let storage = multer.diskStorage({
  destination: (req, file, ca) => { cb(null, 'Images') },
  filename:  (req, file, cb) => { cb(null, file.fieldname + '-' + Date.now()) }
});


const upload = multer({storage: storage})
app.post("/uploadfile", upload.single('image'), (req, res) => {
  console.log(req.files);
})

sslServer.listen(3443, () => console.log('Secure server running on port xxxx'))

JavaScript/Axios/React/html Front-end

import axios from 'axios';
import Button from '@mui/material/Button';
import React,{Component} from 'react';

class App extends Component {

    state = {


    selectedFile: null
    };

    onFileChange = event => {

    this.setState({ selectedFile: event.target.files[0] });
    };

    onFileUpload = () => {

    const formData = new FormData();

    formData.append(
        "myFile",
        this.state.selectedFile,
        this.state.selectedFile.name
    );

    console.log(this.state.selectedFile);

    axios.post("https://xx.xxx.xx.xx:xxxx/uploadfile", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    }
  }).then((response) => {console.log(response)})
   .catch((error) => {console.log(error)});
    };

    fileData = () => {

    if (this.state.selectedFile) {

        return (
        <div>
            <h2>File Details:</h2>
            <p>File Name: {this.state.selectedFile.name}</p>

            <p>File Type: {this.state.selectedFile.type}</p>

            <p>
            Last Modified:{" "}
            {this.state.selectedFile.lastModifiedDate.toDateString()}
            </p>

        </div>
        );
    } else {
        return (
        <div>
            <br />
            <h4>Choose before Pressing the Upload button</h4>
        </div>
        );
    }
    };

    render() {

    return (
        <div>
            <div>
                <input type="file" name="image" onChange={this.onFileChange} />
                <Button
          style={{
            margin: "5%",
            fontFamily: "Nunito, sansSerif",
            fontWeight: "bold",
            fontSize: "20px",
            backgroundColor: "rgb(46, 125, 50)",
            color: "white",
            borderRadius: "0.25rem",
            boxShadow: "rgb(70, 67, 67) 0 0 5px"
          }}
          onClick={this.onFileUpload}
        >Upload!</Button>
            </div>
        {this.fileData()}
        </div>
    );
    }
}

export default App;

error im getting on Node.js

MulterError: Unexpected field
    at wrappedFileFilter (C:\backend\node_modules\multer\index.js:40:19)
    at Multipart.<anonymous> (C:\backend\node_modules\multer\lib\make-middleware.js:107:7)
    at Multipart.emit (node:events:513:28)
    at HeaderParser.cb (C:\backend\node_modules\busboy\lib\types\multipart.js:358:14)
    at HeaderParser.push (C:\backend\node_modules\busboy\lib\types\multipart.js:162:20)
    at SBMH.ssCb [as _cb] (C:\backend\node_modules\busboy\lib\types\multipart.js:394:37)
    at feed (C:\backend\node_modules\streamsearch\lib\sbmh.js:219:14)
    at SBMH.push (C:\backend\node_modules\streamsearch\lib\sbmh.js:104:16)
    at Multipart._write (C:\backend\node_modules\busboy\lib\types\multipart.js:567:19)
    at writeOrBuffer (node:internal/streams/writable:392:12)

i have tried nearly everything, but still nothing

What im trying to get to ? Well, right now i simply want to upload file(any type - file, img, zip, folder) on my front end, that will be send by Axios to my Back end, and then that Back end will receive the file, and save it eee kinda anywhere, lets say root folder or file inside of root folder.

npatrik30
  • 27
  • 4
  • 1
    use upload.single('myFile') instead of upload.single('image') - https://stackoverflow.com/questions/31530200/node-multer-unexpected-field – Dmitriy Mozgovoy Mar 03 '23 at 20:35
  • Thanks, that helped a bit (LOT), a got another error: that say "cb" is not defined but it was here destination: (req, file, ca) => { cb(null, 'Images') }, so i changed cb to ca, and got another error => Error: ENOENT: no such file or directory, open 'C:\Windows\system32\Images\myFile-1677877361053' but its cuz im booting my Node.js from cmd and its located in sys32, so i need to change dir, i had same problem with .env files, i had to do: require('dotenv').config({path: 'C:/backend/.env'}) – npatrik30 Mar 03 '23 at 21:05
  • Okay, I do { ca(null, '../../backend/files') }, created "files" folder, and it Actually worked, now i have myFile-1677877879307 saved in that folder, but how do im gonna read this ? can do somehow it will save in like some usable format ? like if i send image it will save like normal openable image ? – npatrik30 Mar 03 '23 at 21:13

0 Answers0