从angular发送文件然后到节点然后使用post请求请求api?

时间:2017-12-14 17:14:04

标签: javascript angularjs node.js express node-modules

如何将发布数据发送到api。我已经收集了从角度到节点的文件,我可以通过console.log()显示它,但我不知道我从角度获得的数据文件如何使用节点js使用post请求将其发送到api。

我的节点中有这个代码,我正在使用节点js的请求模块。

'use strict';

import _ from 'lodash';
import request from 'request';

function fetch(method, url, req) {
  return new Promise(function(resolve, reject) {
    var options = {
      method: method,
      url: url,
      headers: {
        'Content-Type': 'application/json'
      }
    }
    if (method === 'GET' || method === 'DELETE') {
      options.headers = {};
      options.qs = req.query;
    } else {
      if (method !== 'DELETE') {
        options.body = JSON.stringify(req.body);
      }
    }
    if (req.headers.authorization) {
      options.headers['Authorization'] = req.headers.authorization;
    }
    if (method === 'DELETE') {
      delete options.qs;
    }
    console.log(req.file);
    request(options, function(error, response, body) {
      if (error) {
        return reject(error);
      }
      if (response.statusCode === 500) {
        return reject(body);
      }
      if (response.statusCode === 204) {
        return resolve({status: response.statusCode, body: 'no-content'});
      }
      try {
        var parsed = ( typeof(body) === 'object' ) ? body : JSON.parse(body);
        return resolve({status: response.statusCode, body: parsed});
      } catch(e) {
        return reject('[Error parsing api response]: ' + e);
      }
    });
  });
}

module.exports = {
  get: function(url, req) {
    return fetch('GET', url, req);
  },
  post: function(url, req) {
    return fetch('POST', url, req);
  },
  put: function(url, req) {
    return fetch('PUT', url, req);
  },
  delete: function(url, req) {
    return fetch('DELETE', url, req);
  }
};

1 个答案:

答案 0 :(得分:-1)

// When selecting a file on the front-end you should be able to find the file in: event.target.files[0] for the event you are triggering when selecting a file. 

// You can then send from your front-end to your back-end by using a multipart form data submission:



var formData = new FormData();

formData.append('name', event.target.files[0].name);
formData.append('file', event.target.files[0]);

var config = {
    headers: { 'content-type': 'multipart/form-data' }
};

const url = '/api/your-proper-endpoint/';
// I'm using axios for http requests but you can use whatever 
// you'd like
axios.post(url, formData, config)

// If you're then using something like expressJS on your back-end you can use an npm package like multer to receive your file in your API route.

// https://www.npmjs.com/package/multer


// example route function in ExpressJS which reads saves a file sent from
// the client, saves it temporarily to an empty server side folder I have 
// called uploads, then reads the saved file. From there you could send it 
// again to another API if needed, or you could just send the file to the
// final API in the first place from the client

    const multer = require('multer');
    const xlsx = require('node-xlsx');
    const fs = require('fs');

    module.exports = (req, res) => {
        return new Promise((resolve, reject) => {
            // set current moment for unique file names
            const dt = Date.now();

            // store file using multer so that the it can be parsed later by node-xlsx(or another module method like fs.readFileSync)
            const storage = multer.diskStorage({
                destination: (req, file, cb) => {
                    cb(null, `${__dirname}/uploads`)
                },
                filename: (req, file, cb) => {
                    cb(null, `${file.fieldname}-${dt}.xlsx`)
                }
            });

            const upload = multer({ //multer settings
                storage: storage,
                fileFilter: (req, file, callback) => { //file filter if you want to validate file extensions
                    if (['xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length - 1]) === -1) {
                        return callback(new Error('Wrong file type'));
                    }

                    callback(null, true);
                }
            }).single('file');

            // read multi-part form upload using multer 
            upload(req, res, (err) => {
                if (err) {
                    reject({ err: err });
                } else {
                    try {
                        // parse JSON from excel file stored by multer
                        const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/uploads/${req.file.fieldname}-${dt}.xlsx`));

                        // delete file once finished converting excel to JSON
                        fs.unlink(`${__dirname}/uploads/${req.file.fieldname}-${dt}.xlsx`, (deleteFileErr) => {
                            if (deleteFileErr) {
                                reject({ err: deleteFileErr });
                            } else {
                                resolve(workSheetsFromBuffer);
                            }
                        });
                    } catch (bufferError) {
                        reject({ err: bufferError });
                    }
                }
            });
        });
    };