如何对数组中的每个文件发出POST请求

时间:2018-10-04 08:21:45

标签: javascript node.js angular typescript express

我在angular组件中有一系列拖放文件。我想为每个http://some.url发出POST请求。我正在尝试执行以下操作:

drop.component.ts

public drop(event) {  
    * somehow set droppedFiles *

    let observables = [];

    this.droppedFiles.forEach(file => observables.push(this.uploadFile(file)));
    forkJoin(observables); 
}  

public uploadFile(image) {
    return this.imagesService.saveImage(image, this.tigerId).pipe(first()).subscribe(
        (data: ISaveImageResponse) => {
            console.log(data);

            return;
        },
        error => {
            console.error(error);

            return;
        }
    );
}

images.service.ts

public saveImage(image: File): Observable<ISaveImageResponse> {
    let imageInfo = {
        name: null, type: null, image: null
    };

    imageInfo.name = [image.name, Validators.required];
    imageInfo.type = [image.type, Validators.required];
    imageInfo.image = null;

    let form = this.formBuilder.group(imageInfo);
    form.get('image').setValue(image);

    const formModel = this.prepareFormData(form);

    return this.http.post<any>(
        'http://some.url',
        formModel
    ).pipe(
        map((imageInfo: any) => {
            return imageInfo
        }),
        catchError((error, caught) => {
            return EMPTY;
        })
    );
}

如果我删除单个文件,则可以正常工作。但是,如果有多个文件,请求将变为待处理,但我看不到它们已记录到服务器(即express.js服务器)中。
有什么问题吗?

更新

我已将代码更新为实际的代码:现在uploadImage()返回Observable,并从forkJoin()调用了请求

更新2

Chrome Dev Tools

待处理一段时间后,服务器控制台中出现以下错误:

(node:1291) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 
11 field listeners added. Use emitter.setMaxListeners() to increase limit  

但是根本没有有关请求的信息(对于我所做的任何请求,例如console.log('POST /images');

更新3

用于处理POST请求的服务器端代码:

server.js

const server = express();
const fs = require("fs");
const path = require('path');
const passport = require('passport');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);

server.use(
    session({
        store: new RedisStore({
            url: config.redisStore.url
        }),
        secret: config.redisStore.secret,
        resave: false,
        saveUninitialized: false
    })
);
server.use( passport.initialize() );
server.use( passport.session() );
server.use( cors({ origin: '*' }) );
server.use( bp.json() );
server.use( express.static('uploads') );
server.use( require('./image.routes') );

const port = 9901;

server.listen(port, () => {
    const dir = __dirname + '/uploads';
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }
    console.log('We are live on ' + port);
});  

image.routes.js

const fs = require('fs');
const formidable = require('express-formidable');
const path = require('path');
let router = express.Router();

router.post('/images',
    formidable({
        encoding: 'utf-8',
        uploadDir: path.resolve(__dirname, 'uploads'),
        multiples: true,
        keepExtensions: true
    }),
    (req, res, next) => {
        console.log('\nPOST /images');

        const image = req.fields;
        const data = req.files;

        image.path = data.image.path;

        const file = fs.createReadStream(image.path);

        createImage(image).then(  // createImage() saves image info to db
            result => {
                if (result) {
                    res.status(200).send(result);
                } else {
                    console.error("Cannot save image");
                    res.status(400).send("Cannot save image");
                }
        }).catch(e => console.error(e.stack));
});  

module.exports = router;

2 个答案:

答案 0 :(得分:2)

您不能使用Promise.all处理Rxjs请求。

您可以使用forkJoin一次发出多个Observale请求,

public drop(event) {  
* somehow set droppedFiles *

   let observables = []

   this.droppedFiles.forEach(file => observables.push(this.uploadFile(file)));
   Rx.Observable.forkJoin(observables)
} 

您的uploadFile函数也未返回可观察值

   public uploadFile(image) {
      return this.imagesService.saveImage(image, this.tigerId).pipe(first())
   }

查看示例编号5 here

答案 1 :(得分:0)

尝试使用“ map”或“ for”代替forEach。

public drop(event) {  
    * somehow set droppedFiles *

    Promise.all(this.droppedFiles.map(file => this.uploadFile(file))); 
}