0

I am trying to upload multiple images with the help of multiparty module. I want to upload only a particular kind of images, say whose names are 'image.jpg'. But it's not working when the image does not meet the criteria and I don't get any response. Here is my code.

req.form.on('part', function(part) {
    if (part.filename === 'image.jpg') {
        var out = fs.createWriteStream('image/' + part.filename);
        part.pipe(out);
    } else {
        //Here i want to clear the stream for the next 'part'
    }
});
req.form.on('close', function() {
    res.send('uploaded!');
});

I think I'm not able to clear the readable stream which contains 'part'. I can write that stream and then delete, it works then. But, I don't want to write any image on my file system if it doesn't meet the criteria. How can I achieve that?

4

2 回答 2

3

为了完成 robertklep 的回答,这是另一种使用自定义可写流的可能性,该流将黑洞数据。当你pipe()流向part黑洞时,它会耗尽它的源头。这只是通过在各处使用流而不是使用原始read()函数调用来保持代码的一致性。

req.form.on('part', function(part) {
  var out;
  if (part.filename === 'image.jpg') {
    out = fs.createWriteStream('image/' + part.filename);
  } else {
    out = new stream.Writable();
    out._write = function (chunk, encoding, done) {
      done(); // Don't do anything with the data
    };
  }
  part.pipe(out);
});
于 2013-11-07T16:38:08.727 回答
1

不完全确定这是否可行,但我认为您可以阅读整个part流,直到它用尽:

req.form.on('part', function(part) {
    if (part.filename === 'image.jpg') {
        var out = fs.createWriteStream('image/' + part.filename);
        part.pipe(out);
    } else {
        while (part.read() !== null);
    }
});
于 2013-11-07T14:56:31.493 回答