Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js receive file in HTTP request

I try to create a server, which can receive a file from an HTTP request. I use Postman as user agent and I add a file to the request. This is the request:

POST /getfile HTTP/1.1
Host: localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 9476dbcc-988d-c9bd-0f49-b5a3ceb95b85

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="test.xls"
Content-Type: application/vnd.ms-excel


------WebKitFormBoundary7MA4YWxkTrZu0gW--

But when the request reaches the server I can not find the file in it (I mean in the request). I tried to receive it from the body part of the request, but it returned > {} <. I tried to figure out, how can I refer to the name of the file, but unfortunately I can not find any reference in the request header for the name of the file...

Can anybody help me to find out, what should I do?

like image 717
HowToTellAChild Avatar asked Oct 27 '17 10:10

HowToTellAChild


2 Answers

As a follow up to my comment, you can use the multer module achieve the thing that you want: https://www.npmjs.com/package/multer

const express = require('express');
const multer = require('multer');

const app = express();
const upload = multer();

app.post('/profile', upload.array(), function (req, res, next) {
  // req.body contains the text fields 
});
like image 144
Stavros Zavrakas Avatar answered Sep 21 '22 22:09

Stavros Zavrakas


var app = require('express')();
var multer = require('multer');
var upload = multer();

app.post('/your_path', upload.array(), function (req, res, next) {
  // req.files is array of uploaded files
  // req.body will contain the text fields, if there were any
});
like image 21
Adrian Zhang Avatar answered Sep 17 '22 22:09

Adrian Zhang