Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FormData for AJAX file upload?

This is my HTML which I'm generating dynamically using drag and drop functionality.

<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data"> <fieldset>     <div id="legend" class="">         <legend class="">file demoe 1</legend>         <div id="alert-message" class="alert hidden"></div>     </div>      <div class="control-group">         <!-- Text input-->         <label class="control-label" for="input01">Text input</label>         <div class="controls">             <input type="text" placeholder="placeholder" class="input-xlarge" name="name">             <p class="help-block" style="display:none;">text_input</p>         </div>         <div class="control-group">  </div>         <label class="control-label">File Button</label>          <!-- File Upload -->          <div class="controls">             <input class="input-file" id="fileInput" type="file" name="file">         </div>     </div>     <div class="control-group">              <!-- Button -->          <div class="controls">             <button class="btn btn-success">Button</button>         </div>     </div> </fieldset> </form>  

This is my JavaScript code:

<script>     $('.wpc_contact').submit(function(event){         var formname = $('.wpc_contact').attr('name');         var form = $('.wpc_contact').serialize();                        var FormData = new FormData($(form)[1]);          $.ajax({             url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',             data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},             type : 'POST',             processData: false,             contentType: false,             success : function(data){             alert(data);              }         });    } 
like image 856
Kalpit Avatar asked Jan 10 '14 12:01

Kalpit


People also ask

How do I upload a file to FormData?

Uploading Multiple Files const uploadFile = (files) => { console. log("Uploading file..."); const API_ENDPOINT = "https://file.io"; const request = new XMLHttpRequest(); const formData = new FormData(); request. open("POST", API_ENDPOINT, true); request. onreadystatechange = () => { if (request.

How do you send a file using multipart form data?

Follow this rules when creating a multipart form: Specify enctype="multipart/form-data" attribute on a form tag. Add a name attribute to a single input type="file" tag. DO NOT add a name attribute to any other input, select or textarea tags.

How do I submit an image in FormData?

Using this function you can upload a image through the FormData object, available in the XMLHttpRequest Level 2, it uses the same format a form would use if the encoding type were set to "multipart/form-data". the function search for a input[type=file], and get the data in it.


2 Answers

For correct form data usage you need to do 2 steps.

Preparations

You can give your whole form to FormData() for processing

var form = $('form')[0]; // You need to use standard javascript object here var formData = new FormData(form); 

or specify exact data for FormData()

var formData = new FormData(); formData.append('section', 'general'); formData.append('action', 'previewImg'); // Attach file formData.append('image', $('input[type=file]')[0].files[0]);  

Sending form

Ajax request with jquery will looks like this:

$.ajax({     url: 'Your url here',     data: formData,     type: 'POST',     contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)     processData: false, // NEEDED, DON'T OMIT THIS     // ... Other options like success and etc }); 

After this it will send ajax request like you submit regular form with enctype="multipart/form-data"

Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.

Note: contentType: false only available from jQuery 1.6 onwards

like image 135
Spell Avatar answered Oct 21 '22 08:10

Spell


I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add

type: "POST"

to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:

Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.

  $.ajax({     url: 'Your url here',     data: formData,     type: "POST", //ADDED THIS LINE     // THIS MUST BE DONE FOR FILE UPLOADING     contentType: false,     processData: false,     // ... Other options like success and etc }) 
like image 36
supertemp Avatar answered Oct 21 '22 09:10

supertemp