2

Im trying to upload several files at once via superagent. I know the docs say to use multiple .attach(), but i can't get it to work dynamically.

Is it possible to loop trough an array and repeat .attach()? Or is this done in another way?

Something like this:

  export function uploadTemplateAction(templateFiles, placeholderStrings, questionnaire) {
  return dispatch => {
    dispatch(uploadTemplateRequestAction());

    if(templateFiles){

      Object.keys(templateFiles).forEach(function(key) {
        request.attach('templateFile', templateFiles[key])
      }.bind(this));

    }

    return request
      .post(uploadPOSTUrl)
      .set('Accept', 'application/json')
      .send({"placeholderStrings": placeholderStrings, "questionnaire": questionnaire})
      .end((err, res) => {
        if (err) {
          dispatch(uploadTemplateFailureAction(err, questionnaire));
        } else {
          dispatch(uploadTemplateSuccessAction(res.body, questionnaire));
        }
      });
  }
}
Daniel Storch
  • 327
  • 1
  • 3
  • 15

2 Answers2

4

Yup, that's possible. You would do it something like this:

var req = request.post('/upload');
files.forEach((file)=> {
   req.attach(file.name, file);
});
req.end(callback);

Taken from the react-dropzone docs: https://react-dropzone.js.org/

katzkode
  • 1,911
  • 1
  • 13
  • 18
mikecousins
  • 129
  • 7
0

If you want to fill up an array of files you can do it like this:

var req = request.post('/upload');
files.forEach((file)=> {
   req.attach('files', file);
});
req.end(callback);

Tested on a project of mine ;)

Gabriel
  • 74
  • 8