How to submit multiple files via form and save them with their original filenames?

Describe the problem/error/question

I have a question for optimising my workflow.
For the sake of a simple MWE: The goal is to submit files (pdfs) and manipulate them, then save the content as txt named after the original file (i.e. originalfilename.pdf.txt).
The problem I face, is that when uploading multiple files, I cannot simply link the filename, since it is stored in an array and the final step utilises /files/test/{{ $('On form submission').item.json.data[0].filename }}.txt as filemname.
This references the first item of the array – but for every file I submitted. So my question is: How can I reflect the position in the array so that

  • file 0 gets filename 0
  • file 1 gets filename 1
  • file n gets filename n.

I am quite convinced that I am making a silly mistake here. :frowning: I am not very programming savvy; but would it be possible to utilise /files/test/{{ $('On form submission').item.json.data[i].filename }}.txt and create a for loop? I am uncertain however, how to implement this in the field itself.

I was able to circumvent the problem by adding a split out and merge node that merges the binary data with the split information of the array. But I guess, it must be possible in a more efficient way?

What is the error message (if any)?

In the current state, all files are written to the same filename, which leads to one file being generated and overwritten n times. ( It is clear to me, that this happens due to the reference of the first item of the array. ) I am looking for a way to adress array positions dynamically according to the item being processed.

Please share your workflow

Share the output returned by the last node

Information on your n8n setup

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

You could split the list before you write, these steps might help:

  1. Add an “Item Lists → Split Out Items” node right after On form submission.
  2. Tell it to split the field data.
  3. From that point on every file is a separate item.
  4. In Read/Write Files from Disk set the filename to /files/test/{{$json.filename}}.txt

If you prefer to keep your current flow, change the filename expression to:
/files/test/{{$json.data[$itemIndex].filename}}.txt

$itemIndex is the position of the item being processed (0, 1, 2 …).
That picks the correct name for each pass and stops the overwrites.

You could also do some crosschecks, see if all files stored inside one array are called data, or are they already separate items?

Hope this helps, cheers! :slight_smile:

2 Likes

Thank you very much!
This was exactly what I was looking for.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.