Angular File Upload

后端 未结 12 2000
名媛妹妹
名媛妹妹 2020-11-22 10:04

I\'m a beginner with Angular, I want to know how to create Angular 5 File upload part, I\'m trying to find any tutorial or doc, but I don\'t see anything a

12条回答
  •  悲哀的现实
    2020-11-22 10:56

    Complete example of File upload using Angular and nodejs(express)

    HTML Code

                

    TS Component Code

    uploadFile(files) {
        console.log('files', files)
            var formData = new FormData();
    
        for(let i =0; i < files.length; i++){
          formData.append("files", files[i], files[i]['name']);
            }
    
        this.httpService.httpPost('/fileUpload', formData)
          .subscribe((response) => {
            console.log('response', response)
          },
            (error) => {
          console.log('error in fileupload', error)
           })
      }
    

    Node Js code

    fileUpload API controller

    function start(req, res) {
    fileUploadService.fileUpload(req, res)
        .then(fileUploadServiceResponse => {
            res.status(200).send(fileUploadServiceResponse)
        })
        .catch(error => {
            res.status(400).send(error)
        })
    }
    
    module.exports.start = start
    

    Upload service using multer

    const multer = require('multer') // import library
    const moment = require('moment')
    const q = require('q')
    const _ = require('underscore')
    const fs = require('fs')
    const dir = './public'
    
    /** Store file on local folder */
    let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public')
    },
    filename: function (req, file, cb) {
        let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
        cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
    }
    })
    
    /** Upload files  */
    let upload = multer({ storage: storage }).array('files')
    
    /** Exports fileUpload function */
    module.exports = {
    fileUpload: function (req, res) {
        let deferred = q.defer()
    
        /** Create dir if not exist */
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir)
            console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
        }
    
        upload(req, res, function (err) {
            if (req && (_.isEmpty(req.files))) {
                deferred.resolve({ status: 200, message: 'File not attached', data: [] })
            } else {
                if (err) {
                    deferred.reject({ status: 400, message: 'error', data: err })
                } else {
                    deferred.resolve({
                        status: 200,
                        message: 'File attached',
                        filename: _.pluck(req.files,
                            'filename'),
                        data: req.files
                    })
                }
            }
        })
        return deferred.promise
    }
    }
    

提交回复
热议问题