简体   繁体   中英

How can I send file from postman to node js?

I want to upload file from postman to node js but I have problem. POSTMAN Write url,check post method,check form-data,check file,write file name and choose file This is my code app.js

const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');

app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

router.js

router.post('/schedule/entry', function(req,res){
   console.log(req.file.name);
});

Console return me undefined name, if I write this code

router.post('/schedule/entry', function(req,res){
   console.log(req.file);
});

Return 'undefined' Why?

package.json

  {
   "name": "nodejs-rest-api-authentication",
   "version": "1.0.0",
   "description": "",
   "main": "app.js",
   "scripts": {
   "start": "node server.js",
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
  "bcryptjs": "^2.4.3",
  "body-parser": "^1.16.1",
  "csv-array": "0.0.22",
  "csv-write-stream": "^2.0.0",
  "express": "^4.14.1",
  "express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
  }
 }

server.js

const app = require('./app');
const port = process.env.PORT || 3000;

const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});

screenshots screenshots

codeGit

Based on the discussion in the comment section:

const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js

app.post('/', (req, res) =>{
  var form = new formidable.IncomingForm()
  form.multiples = true
  form.keepExtensions = true
  form.uploadDir = uploadDir
  form.parse(req, (err, fields, files) => {
    if (err) return res.status(500).json({ error: err })
    res.status(200).json({ uploaded: true })
  })
  form.on('fileBegin', function (name, file) {
    const [fileName, fileExt] = file.name.split('.')
    file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
  })
});


app.listen(3000, () => console.log('Example app listening on port 3000!'))

Attached Screenshots在此处输入图片说明 : 在此处输入图片说明

在此处输入图片说明

由于正文解析器中间件文件在 req 中不可用,因此您必须使用其他中间件库,例如connect-busboy multermulterconnect-multiparty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM