如何使用Angular js上传文件,&存储在mongodb的图像路径

时间:2017-07-30 05:47:48

标签: angularjs node.js mongodb angular-file-upload


我有一个带有文字字段和表格的表单。下拉菜单。
我正在使用 Node.js,Angular js,Express,MongoDb
我想发布数据和图像。
我想将图像存储在文件夹中,没有任何基本/二进制转换,图像路径应存储在mongoDb中。
我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:0)

前端:

<强> HTML:

<input type="file" nv-file-select uploader="vm.uploader"
       id="fileUpload" ng-model="vm.schema.file"/>Browse

<强>控制器:

  angular
  .module('myApp')
  .controller('myController', myController);

  myController.$inject = ['FileUploader'];

  function EditSchemaBasicController(FileUploader) {
    vm.uploader = new FileUploader({
          url: "https://localhost:3000/api/file", //your api URL
          queueLimit: 10, 
          onAfterAddingFile: function(item) {
            //before upload logic will go here like file size and extension handling
            item.upload();
          },
          onCompleteItem: function(item, response){
            //on complete
            console.log('Uploaded File: ' + response.file);
          },
          onErrorItem: function(item, response) {
            //error handling
          }
        });
    }

后端:

'use strict'
var express = require('express');
var router = express.Router();
var fs = require('fs-extra');

//Post file.. i used busboy to upload the file
router.post('/', function(req, res, next) {
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {    
    filename = decodeURI(filename);
    //Path where file will be uploaded
    var fstream = fs.createWriteStream('API/Images' + filename);
    file.pipe(fstream);
    fstream.on('close', function () {
      res.status(201).json({file: filename});
    });
  });
});

module.exports = router;

答案 1 :(得分:0)

您可以使用简单/轻量级ng-file-upload指令。它支持拖放。

<div ng-controller="MyCtrl">
  <input type="file" ngf-select="onFileSelect($files)" multiple>
</div>

JS:

angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
  $scope.onFileSelect = function($files) {
  Upload.upload({
    url: 'api/upload',
    method: 'POST',
    file: $files,            
  }).progress(function(e) {
  }).then(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  }); 

}];

您可以使用formidable来解析表单数据,尤其是文件上传。阅读更多here

app.post('/api/upload', function(req, res) {
    var form = new formidable.IncomingForm();


    form.multiples = true;

    form.uploadDir = path.join(__dirname, '../../public/images');


    form.on('file', function(field, file) {

        //copy file to new path
        fs.renameSync(file.path, path.join(form.uploadDir, file.name));

        var Image = path.join(form.uploadDir, file.name);
        //save new path to mongodb

        db.collection('images').insert({
            imagePath: Image
        }, function(err, result) {
            // do your stuff
        })


    });
})

这只是我的建议。你应该学到更多,做你期望的事。希望它有所帮助。

答案 2 :(得分:0)

HTML文件

<input class="form-control" type="file" name="photo" ng2FileSelect [uploader]="uploader" (change)="uploader.uploadAll()"/>
<button (click)="addBusiness()" class="btn btn-primary"> Add Business </button>

组件文件

public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'angular'});
addBusiness() {
var uploadImages = this.uploader.queue[0].file.name;
this.bs.addBusiness(uploadImages);}

服务文件

uri = 'http://localhost:4000/business';
addBusiness(uploadImages) {
const obj = {uploadImages: uploadImages};
this.http.post(`${this.uri}/add`, obj)
    .subscribe(res => console.log('Done'));

}

服务器文件

const DIR = '../src/assets/upload';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
  cb(null, DIR);
},
filename: (req, file, cb) => {
  console.log(file);
  cb(null, file.originalname);
}
});
let upload = multer({storage: storage});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.post('/api/upload',upload.single('angular'), function (req, res) {
if (!req.file) {
  console.log("No file received");
  return res.send({
    success: false
  });
} else {
  console.log('file received');
  return res.send({
    success: true
  })
}
});

路由器文件

const express = require('express');
const businessRoutes = express.Router();
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Define collection and schema for Business
let Business = new Schema({
uploadImages: {
type: String
}},{
collection: 'business'
});
let Business = mongoose.model('Business', Business);
businessRoutes.route('/add').post(function (req, res) {
let business = new Business(req.body);
business.save()
.then(business => {
  res.status(200).json({'business': 'business in added successfully'});
})
.catch(err => {
  res.status(400).send("unable to save to database")
});
});