Home > Software design >  Uploading a File by Path - DocParser API
Uploading a File by Path - DocParser API

Time:10-13

So am I currently trying to Upload a file to parser using the DOCPARSER API, however whenever I try to upload the file I just get a response that states the "received contents have 0 bytes". The file currently uploads to the "uploads" directory fine for now, also here is the API documentation: https://github.com/Docparser/Docparser-Node

const express = require('express');
const path = require('path');
const docparser = require('docparser-node');
const client = new docparser.Client("API KEY");
const fileUpload = require('express-fileupload');


const app = express();

app.use(fileUpload());

// Upload Endpoint
app.post('/upload', (req, res) => {
  if (req.files === null) {
    return res.status(400).json({ msg: 'No file uploaded' });
  }

  const file = req.files.file;


  console.log(file);


  file.mv(`${__dirname}/../client/public/uploads/${file.name}`, err => {
    if (err) {
      console.error(err);
      return res.status(500).send(err);
    }

    res.json({ fileName: file.name, filePath: `/uploads/${file.name}` });
  });



  client.uploadFileByPath('cslfmvewjrvo', `${__dirname}/../client/public/uploads/${file.name}`)
  .then(function (result) {
    // => {"id":"document_id","file_size":198989,"quota_used":16,"quota_left":34,"quota_refill":"1970-01-01T00:00:00 00:00"}
    promise.resolve(console.log(result));
  })
  .catch(function (err) {
    console.log(err)
  })

});

app.listen(3000, () => console.log('Server Started...'));

CodePudding user response:

Seems that your problem was a syncronous one... Your client block was expecting a file but you can't guarantee that file.mv is ready, so I did some modifications and using multer instead of fileUpload and other method of DocParser for upload uploadFileByStream:

const express = require('express');
const docparser = require('docparser-node');
const client = new docparser.Client("CLIENT_ID");

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
})

const upload = multer({ storage });

const fs = require('fs')


const app = express();

// Upload Endpoint
app.post('/upload', upload.single('file'), (req, res) => {
  if (req.file === null) {
    return res.status(400).json({ msg: 'No file uploaded' });
  }

  const file = req.file;

  console.log(`${__dirname}/uploads/${file.filename}`);

  client.uploadFileByStream('PARSE_ID', fs.createReadStream(`${__dirname}/uploads/${file.filename}`))
    .then(function (result) {
      Promise.resolve(console.log(result));
    })
    .catch(function (err) {
      console.log(err.stack)
    })

  res.json({ fileName: file.name, filePath: `/uploads/${file.filename}` });

});

app.listen(3000, () => console.log('Server Started...'));
  • Related