Ajax File Upload

jQuery Ajax File Upload

File upload is not possible through AJAX.

You can upload file, without refreshing page by using IFrame.

You can check further details here.


UPDATE

With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

How to upload a file using Ajax on POST?

Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.

If you are using JQuery solely for the use of ajax, then I recommand using axios:

const axios = require('axios');

var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);

axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});

Axios Documentation


Jquery/Ajax answer:

var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security

$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});

Jquery/Ajax Documentation

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.

Your HTML is fine, but update your JS jQuery script to look like this:

(Look for comments after // <-- )

$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:

<?php

if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],

// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

Uploading both data and files in one form using Ajax?

The problem I had was using the wrong jQuery identifier.

You can upload data and files with one form using ajax.

PHP + HTML

<?php

print_r($_POST);
print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>

jQuery + Ajax

$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);

$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});

Short Version

$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);

$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});

How to use FormData for AJAX file upload?

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

How to upload a file using an ajax call in flask

To answer your question...

HTML:

<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn" type="button">Upload</button>
</fieldset>
</form>

JavaScript:

$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/uploadajax',
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});

Now in your flask's endpoint view function, you can access the file's data via flask.request.files.

On a side note, forms are not tabular data, therefore they do not belong in a table. Instead, you should resort to an unordered list, or a definition list.



Related Topics



Leave a reply



Submit