0

I have a file input element outside the form. and on form submit i want to send the file content to server as multipart form data. I can't insert the file element into the form. Is there any other way to do this.

<input type="file" class="file"  style="width:117px"  name="c2vFile" onchange="onFileChange2(this.value);"/>

    <form style="display:none" id="frmActivate" enctype="multipart/form-data">

        <input type="hidden" id="act_groupActivationJson" name="groupActivationJson" />
        <input type="hidden" id="act_remarks" name="comments" />
        <input type="hidden" id="activatee" name="activatee" />

    </form>
Abhinav Parashar
  • 619
  • 4
  • 11
  • 27

3 Answers3

0

The file input needs to be inside the form tag. You've mentioned you can't, but why not? You would need to remove the "display:none", which serves no purpose currently, as the inputs are all hidden.

user1751825
  • 4,029
  • 1
  • 28
  • 58
0

You can send a file outside of form tag using AJAX submission. You can follow the below link will helpful for sending file using ajax. But you have have to invoke this function on click of submit button. Once the file upload done then form submit should be happen.

jQuery Ajax File Upload

Community
  • 1
  • 1
Nalla Srinivas
  • 913
  • 1
  • 9
  • 17
0

I did a small trick with this and it worked, please review if it is helpful for you Before submitting the form add listener and append the input field with the form.

document.getElementById('frmActivate').addEventListener("submit", function() {
  var fileinput = document.getElementById('filein');//take the file input 

  var thisel = document.getElementById('frmActivate');// take the form element
  var cln = fileinput.cloneNode(true);//clone the file input element
  thisel.appendChild(cln);//append the clone in the form element
  thisel.submit();
 
})
<input type="file" id="filein" class="file" style="width: 117px" name="c2vFile" onchange="onFileChange2(this.value);" />
<form style="" id="frmActivate" enctype="multipart/form-data">
  <input type="hidden" id="act_groupActivationJson" name="groupActivationJson" />
  <input type="hidden" id="act_remarks" name="comments" />
  <input type="hidden" id="activatee" name="activatee" />
  <input type="submit" value="submit" />
</form>
<?php var_dump($_FILES);//to confirm if file is submitted ?>
You can see this code working in this demo Hope this works for you.
Asim Khan
  • 572
  • 6
  • 34