-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)
   })
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
Omair K.
  • 3
  • 3
  • 1
    Welcome to Stack Overflow. Please add a brief description, code, errors of your search/research efforts as is suggested. – Prathamesh More Sep 25 '20 at 13:53
  • Does this answer your question? [How to upload files using React?](https://stackoverflow.com/questions/46233585/how-to-upload-files-using-react) – Prathamesh More Sep 25 '20 at 13:54

2 Answers2

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
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]

Omair K.
  • 3
  • 3
  • 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 – Omair K. Sep 28 '20 at 06:31
  • What will the result is we console event.target.files[0] you know. I want that result from backend file to console – Omair K. Sep 28 '20 at 06:34