2

Please tell me how I can upload a file to express.js server witch use bodyparser.raw()

  • client side
<input type='file' @change='onFilePicked' />
// ...
onFilePicked(file) {
  const url = 'upload/api/url';
  let fd = new FormData();
  fd.append('upload', file);
  fd.append('key', 'somestring');
  axios.post(url,fd).then( res => { console.log(res); }, err => { console.log(err); });
}
// ...
  • server side
const app = express();
app.use(bodyParser.raw());

app.post('upload/api/url', (res, req) => {
  console.log(req.req.key); //undefined
  console.log(req.req.upload); //undefined

  res.res.status(500).send("WIP");
});

I have to use bodyparser.raw(). Maybe can I pul form data as value into json object?

I can not read file content inside app.post('upload/api/url', ... );.

3
  • I think req.req.key is a typo? Try to console.log(req.body) Commented Mar 3, 2020 at 11:52
  • req object is given as function param and it is ServerResponse type. req.req is a field of req and it is IncomingMessage type. So req.req in my code is equal to ServerResponse.req ... Commented Mar 3, 2020 at 12:03
  • conosle.log(req.body) => udefined / conosle.log(req.req.body) => {} Commented Mar 3, 2020 at 12:21

1 Answer 1

1

Look at: https://stackoverflow.com/a/40411508/9018487 and: https://www.npmjs.com/package/multer

  • client side
// ...
onFilePicked(file) {
  const url = 'upload/api/url';
  let fd = new FormData();
  fd.append('upload', file);
  fd.append('key', 'somestring');
  axios.post(url,fd, {
    headers: {
      ...
      'Content-Type':'multipart/form-data'
    }
  })
  .then( res => { console.log(res); }, err => {console.log(err); });
}
// ...
  • server side
const multer = require("multer");
const upload = multer({dest: "/data/"});

const app = express();
app.use(bodyParser.raw());

app.post('upload/api/url', multer.single('upload'), (res, req) => {
  console.log(req.req.file);
/*
{
  fieldname: 'upload',
  originalname: 'somefile.txt',
  encoding: '7bit',
  mimetype: 'text/plain',
  destination: 'tmp/',
  filename: '564968d9611fa809e4b32233854f12aa',
  path: 'data/564968d9611fa809e4b32233854f12aa',
  size: 93038
}
*/

  // TODO:
  // 1. Open and read file req.req.file.path to local variable
  // 2. Remove file req.req.file.path
  // 3. Do something with data from file

  res.res.status(500).send("WIP");
});

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

Comments

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.