arnekolja
arnekolja

Reputation: 1687

File upload via hidden iFrame - form nesting problem

I assume this one is rather a JavaScript/jQuery/DOM question than a Rails question, but it's all due to the way I implemented it in Rails.

I am trying to upload files while creating a new object (auction). While the user inputs some data, he shall also have the possibility to upload multiple photos.

The main problem is, that the files should be uploaded while filling out the form. And the form is a tabbed one, so the photos are on tab 3 of 5 and all tabs sit within the overall create form. That means, that the upload form has to be (DOM position) within the main form for creating the object, which is not allowed by the HTML specification.

To avoid nesting forms I tried to jQuery.clone() the file field when submitting the photo first, so I can create the upload form on the fly - but this didn't work, as JS doesn't seem to be able to access the value of a file field.

So my question is: how could I implement such a "submit form to hidden iframe" thingy, when I can't avoid to place the upload-only form within another form, from a DOM point of view? Does anyone know a good hint or something?

Thanks in advance for your help

Arne

Upvotes: 2

Views: 3677

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114447

Ok, assuming you have one form, you can do the following:

  • Set the target of your form to point to the name of the Iframe. The POST with the file upload will occur in the background, targeting the Iframe.
  • Use window.setTimeout(function() {document.form1.target=''},1) to clear the target after when your form submits.
  • Continue using the form as normal.

If course it's a little easier if you have multiple forms, that way you can just point the file upload form to that target by itself.

EDIT - Try this:

<form id="upload-form" target="myiFrame"><input type="file" /></form>
<form action="/model/create"></form>
<iframe name="myiFrame" src="/model/upload"></iframe>

Upvotes: 3

Related Questions