Home > Net >  How to access uploaded data from a loop?
How to access uploaded data from a loop?

Time:10-01

In the frontend I've a very large form where I can also upload images. I thought it would be better to upload and save the images immediately and then again retrieve the uploaded images in the frontend. Then I can add all the other necessary data to the form. After the form is completely filled out, I would like to save the entire form (with the newly received images-data) to the database. Hopefully this makes sense?

So, in the backend I want to send the uploaded files to the frontend. Because uploadFiles is contained in a loop, I don't know how to access it outside of it.

exports.uploadFiles = async (req, res) => {
  const filesArray = req.files;
  console.log(filesArray);

  try {
    for (const file of filesArray) {
      const uploadFiles = new FilesStorage({
        filePath: file.location,
      });

      await uploadFiles.save();
    }

    return res.status(200).json({
      success: true,
      message: "Files successfully uploaded",
      files: uploadFiles // <-- I want to achieve this
    });
  } catch (err) {
    console.log(err);
    return res.status(500).json({
      success: false,
      message: `Something wen't wrong`,
    });
  }
};

CodePudding user response:

I suggest you use Promise.all to map all the filesArray together and return the saved files.

exports.uploadFiles = async (req, res) => {
    const filesArray = req.files;
    console.log(filesArray);

    try {
        const uploadedFiles = await Promise.all(
            filesArray.map(async (file) => {
                const uploadedFile = new FilesStorage({
                    filePath: file.location,
                });

                await uploadFiles.save();
                return uploadedFile;
            })
        );

        return res.status(200).json({
            success: true,
            message: "Files successfully uploaded",
            files: uploadedFiles, // <-- I want to achieve this
        });
    } catch (err) {
        console.log(err);
        return res.status(500).json({
            success: false,
            message: `Something wen't wrong`,
        });
    }
};

  • Related