-1
 var title="this is title";
  var content="this is content";
  const config = { headers: {'Accept': 'application/json', 'Content-Type': 'multipart/form-data' } };
  const form = new FormData()
  let file =event.target.files[0]
  form.append('file', file)
 form.append('title', title)
   form.append('content', content)`enter code here`
Axios.post("http://localhost:3001/article/get/123", form,config ).then((res)=>{
     console.log(res.data)
   })
2
  • 1
    Welcome to Stack Overflow. Please add a brief description, code, errors of your search/research efforts as is suggested. Commented Sep 25, 2020 at 13:53
  • Does this answer your question? How to upload files using React? Commented Sep 25, 2020 at 13:54

2 Answers 2

1

in node I have used multer for upload image or anything.

Below is the code for upload which I have used as a middleware.

const util = require("util");
const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({ 
    destination: function (req, file, cb) {
        cb(null, "./Uploads") // folder path where to upload
    }, 
    filename: function (req, file, cb) { 
      cb(null, file.originalname + "-" + Date.now() + path.extname(file.originalname))
    } 
  });

const maxSize = 1 * 20000 * 20000; // file size validation

const uploadFiles = multer({ storage: storage, limits: { fileSize: maxSize } }).array("myfiles", 10); // key name should be myfiles in postman while upload

const uploadFilesMiddleware = util.promisify(uploadFiles);

module.exports = uploadFilesMiddleware;

Below is the function which I have created in controller for upload and file check.

fileUpload = async (req, res) => {
  try {
        let userCode = req.headers.user_code;
        await upload(req, res);
        if (req.files.length <= 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Kindly select a file to upload..!!', true));
        }
        let response = [];
        for (const element of req.files) {
            let data =  await service.addFileData(element, userCode);
            response.push(data); // for file path to be stored in database
        }
        if (response && response.length > 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators(response, httpStatusCode.OK, 'File uploaded sucessfully..!!', false));
        } else {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Failed to upload file kindly try later..!!', true));
        }
      } catch (error) {
            logger.warn(`Error while fetch post data. Error: %j %s`, error, error)
            return res.status(httpStatusCode.INTERNAL_SERVER_ERROR).send(responseGenerators({}, httpStatusCode.INTERNAL_SERVER_ERROR, 'Error while uploading file data', true))
        }
    }

and the route will go like this.

router.post('/upload/file', fileUploadController.fileUpload);

And be sure to keep same name in postman while file upload as in middleware.

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

Comments

0

The above code is in react.js. I want to do same work in node.js and the file will be upload from the public folder. main issue is how to upload image file in format like we have in frontend event.target.files[0]

2 Comments

Basically i want to sent a image file from node server to python server locally. And my image file is in public folder. So how i can send image file to python server
What will the result is we console event.target.files[0] you know. I want that result from backend file to console

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.