How do I upload a FilePond file field to the server along with other form elements. For example i have a form element that contains input fields, a select field, a textarea and a file input field which is connected to the Filepond plugin.
<form class="uploadform"> <input type="text" placeholder="type the title of the document you are uploading"> <textarea class="textarea" placeholder="type anything here"></textarea> <input type="file" class="filepond" name="file[]" multiple> <button type="button" class="uploadbtn">Upload Document</button> </form>
But whenever i try to upload the form the file field doesn’t upload with it to the server, please help me with this. How do i bind the FilePond input field to my formdata element?
This is my jQuery upload code:
$(".uploadbtn").click(function(){ var form = document.getElementsByClassName("uploadform")[0] var formdata = new FormData(form) $.ajax({ url: "path/to/php-server-side/request/handler.php", data: formdata, processData: false, contentType: false, method:"post" }).done(function (response) {... })
Advertisement
Answer
You need to append FilePond files manually to the FormData object. FilePond objects has a file
property which is the original file blob object. You can go like this:
$(document).ready(function(e){ pond = FilePond.create( document.querySelector('#file'), { allowMultiple: true, instantUpload: false, allowProcess: false }); $("#uploadform").submit(function (e) { e.preventDefault(); var formdata = new FormData(this); // append FilePond files into the form data pondFiles = pond.getFiles(); for (var i = 0; i < pondFiles.length; i++) { // append the blob file formdata.append('file[]', pondFiles[i].file); } $.ajax({ url: "path/to/php-server-side/request/handler.php", data: formdata, dataType: 'JSON', processData: false, contentType: false, method:"post" }).done(function (response) { // todo }); }) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script> <script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script> <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/> <script src="https://unpkg.com/filepond/dist/filepond.js"></script> <form id="uploadform" enctype="multipart/form-data"> <input type="text" placeholder="type the title of the document you are uploading"> <br> <textarea class="textarea" placeholder="type anything here"></textarea> <input id="file" type="file" class="filepond" name="file"> <button type="submit" class="uploadbtn">Upload Document</button> </form>
With this, you’ll get the files as if they where sent by html
form.