使用nodejs以角度2上传文件

时间:2017-06-17 08:31:32

标签: node.js angular

我是角度2和节点js的新手。 我需要使用anjular2在文件夹中上传文件,并且还希望将该文件名存储在服务器端的mongodb数据库中。为此,我尝试了这个,但它不工作。使用代码是: app.component.ts:

        attachment: any;
       hasBaseDropZoneOver: boolean = false;
        options: Object = {
        url: 'http://localhost:3000/upload'
        };
        sizeLimit = 2000000;
        handleUpload(data): void {
        if (data && data.response) {
        this.attachment = data;
        }
        }
        fileOverBase(e:any):void {
        this.hasBaseDropZoneOver = e;
        }
        beforeUpload(uploadingFile): void {
        console.log(uploadingFile.size + ' -- '+this.sizeLimit);
        if (uploadingFile.size > this.sizeLimit) {
        uploadingFile.setAbort();
        alert('File is too large');
        }
        }

这是app.html文件: -

        <input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)" (beforeUpload)="beforeUpload($event)">

app.module.ts

        import { Ng2UploaderModule } from 'ng2-uploader';

服务器端代码:

        const upload = multer({
        dest: 'uploads/',
        storage: multer.diskStorage({
        filename: (req, file, cb) => {
        let ext = path.extname(file.originalname);
        cb(null, `${Math.random().toString(36).substring(7)}${ext}`);
        }
        })
        });
        app.post('/upload', upload.any(), (req, res) => {
        res.json(req.files.map(file => {
        let ext = path.extname(file.originalname);
        return {
        originalName: file.originalname,
        filename: file.filename
        }
        }));
        });

它向我显示以下错误:

        XMLHttpRequest cannot load http://localhost:3000/upload. Response to preflight request doesn't pass access 

0 个答案:

没有答案