简体   繁体   中英

req.body is Empty on angular file-upload, node js

so I've been working on uploading an excel file then save it to the database. so this is the form.

<form method="post" enctype="multipart/form-data">

   <label class="uk-form-file md-btn md-btn-primary" for="user_upload">Upload File</label>
        <input 
            style="display:none;"
            type="file" 
            ngf-select 
            ng-model="user_datasource" 
            name="userdatasource_upload" 
            id="userdatasource_upload"
            accept=".xlsx,.xls,.csv"
            ngf-max-size="20MB" 
            fd-input
            ng-change="upload"/>
 </form>

this is my controller that handles my upload

$scope.upload = function() {
  Upload.upload({
      url: '/api/sr/user_upload',
      data: {
         username: 'test',
         file: file_upload
      }
  }).then(function(response) {
     console.log(response);
  });      
}

and this is my node

app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Allow-Origin", "http://127.0.0.1:3000");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

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

app.post('/api/sr/user_upload',function(req, res) {
  console.log('============================================,');
  console.log(req);
}); 

so as you can see. I include everything. body-parser , setHeader etc. but with no luck. the req.body is empty. going to upload a file then save it to the database with username. after I get the username then im going to use the multer please help me out! thanks!

As you are using multer on the basis of this I am writing this answer

The multer saves files first, and then writes to req the remaining part of the form - can say hidden field.

So you need to get your rest data in upload function like this

upload(req, res, function(err) {
    if (err) {
        console.log(err);
        return res.end('Error');
    } else {
        console.log(req.body);
        req.files.forEach(function(item) {
            console.log(item);
            // move your file to destination
        });
        res.end('File uploaded to Destination');
    }
});

Hope this will work for you

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