Sending input[type=file] through ajax to CodeIgnit

2019-08-29 09:28发布

问题:

Here is the basic html form:

<?php echo form_open( 'controller' ); ?>  
  <fieldset>
    <input type="text" name="field_name_1" value="<?php echo set_value('field_name_1'); ?>"/>
    <input type="file" name="field_name_2" value="<?php echo set_value('field_name_2'); ?>"/>
    // more dynamically added form fields
    <input type="submit" />
  </fieldset>
<?php echo form_close(); ?>

I want my input[type=file] to be sent to its controller (together with the other input types as one) via ajax and the jQuery Form Plugin.

I have the code below that works on all the other input types except for input[type=file].

<script src="http://malsup.github.com/jquery.form.js"></script> 

var options = {
    url: "<?php echo site_url('new_account/validate_new_account'); ?>",
    type: 'POST',
    dataType: 'json',
    success: function(data) {

      if (data.length === 0) {
        alert('Form successfully submitted!');
      } else {
        alert("Some fields weren't answered successfully. Please answer them.");
        // attach server-side form validations to respective fields
        $.each(data, function(key, value){
          var container = '<div class="error">'+value+'</div>';
          $('.form-element input[name="'+key+'"]').after(container);
        });
      }

    }
};

$('#main-submit').click(function(e) {
  $('#professional-form').valid(); // jQuery validate
  $('#professional-form').ajaxSubmit(options);  
  e.preventDefault(); // redirect to other place only if successful form 
});

The other input fields are sent successfully but CodeIgniter still does not receive the file. Do you guys know how to fix this?

回答1:

File upload is not generally possible via standard ajax posting. However there are certain tools out there that allow asynchronous uploading of files:

  • http://blueimp.github.com/jQuery-File-Upload/
  • http://www.plupload.com/

The reason you can't do this using a standard jquery post is because javascript can't read local files for security reasons. These tools get around the limitation using various solutions such as hidden iframes, Flash, or HTML5 techniques, depending on what is available on the browser.



回答2:

File upload is possible via ajax with jquery.form.js as mentioned on the following link:

http://malsup.com/jquery/form/#file-upload