How to write Node.js express API to upload files?

There are many examples on the Internet related to downloading files for the Node.js Express framework. But most of them use multer . They all upload a file from the form.

But my script is different. My application will display an image from a mobile phone and upload to the server (using the cordova-file-transfer in Ionic plugin). In this case, I have no form at all. So there is no req.files. Any suggestion? Thanks.

PS: Here is the log of my server logs my http header:

{ host: 'localhost:3000',
  'x-requested-with': 'XMLHttpRequest',
  accept: '*/*',
  'content-type': 'multipart/form-data; boundary=+++++org.apache.cordova.formBoundary',
  'content-length': '23394',
  'accept-language': 'en-us',
  'accept-encoding': 'gzip, deflate',
  connection: 'keep-alive',
  'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 (2079040640)' }

My server code:

  app.post('/', multer({dest:'./uploads/'}).single('upl'),(req,res) => {
    console.dir(req.headers)
    console.dir(req.body)
    res.status(204).end()
  })

Apparently, "upl" is not defined in my case.

+4
1

- , .

, cordova-file-transfer node.js express server.

app.js:

var express = require('express')
var multer = require('multer')
var bodyParser = require('body-parser')
var path = require('path')

var app = express()

// settings
app.set('views', path.join(__dirname,'views'))
app.set('view engine','jade')

// middleware
app.use(bodyParser.json())

// route
app.get('/', (req,res) => {
  res.render('index')
})

app.post('/', multer({dest:'./uploads/'}).single('upl'),(req,res) => {
  console.log(req.body)
  console.log(req.file)
  res.status(204).end()
})

// start
var server = app.listen(3000, () => {
  console.log('Started at port ' + server.address().port)
})

upload():

upload() {

var options = new FileUploadOptions()
options.fileKey = "upl";              // this equal to <input type="file" id="upl">
options.fileName = 'test.jpg';
options.mimeType = "image/jpg";
options.chunkedMode = false;
options.params = {'directory' : 'uploads', 'fileName': 'test.jpg'};

var ft = new FileTransfer()
ft.upload(this.thumbnail, encodeURI('http://localhost:3000/'),
  (res) => {
    console.log("Code = " + res.responseCode)
    console.log("Response = " + res.response)
    console.log("Sent = " + res.bytesSent)
  },(error) => {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
  },options)
}

this.thumbnail - , , ios, :

:////MyUserName/Library/Developer/CoreSimulator/Devices/81B513B7-AE34-4911-A9C9-57E293957BEC///Data/Application/C9A0BE15-EA4A-4DD8-9E75-BC960ECF50B7/TMP/cdv_photo_016.jpg

+5

Source: https://habr.com/ru/post/1627403/


All Articles