I have a really simple HTML page with an image upload form as follows:
<form id="file_data">
<input type='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
My Javascript:
$(document).ready(function() {
$("form[id='file_data']").submit(function() {
var form_data = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
upload.php is creating a directory to store images, if the directory does not already exists. Then is supposed to store image in the directory:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
While the PHP script will create the directory, if it does not already exist, it is not saving any images to the directory. I'm assuming I am not accessing the image correctly from PHP, but the tutorials I've looked at don't explain too much of the details of what is actually going on when an image is sent in an Ajax call to PHP.
Problem you are missing in code:
Html: enctype="multipart/form-data" on form to upload file, also <input type="file" missing name="file"
Php: move_uploaded_file is not correct you are missing ['file'] for tmp_name $_FILES['file']["tmp_name"]
Ajax: dataType:"html" is missing so that your ajax get response as string from server
Update your Html, Php and Ajax code like this:
Html Code:
<form id="file_data" enctype="multipart/form-data" method="post">
<input type='file' name='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
Php Code:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES['file']["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
Ajax Code:
$.ajax({
url: "upload.php",
data : form_data,
type : "POST",
async: false,
cache: false,
contentType: false,
processData: false,
dateType : "html",
success: function(data) {
alert(data);
}
});
Related
I am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 7 years ago.
I'm trying to make an image uploader with php and jquery but i can't get it to work.
My question is
Why is $_FILES['image']; empty?
Heres my code
Html
index.php
<form id="uploadForm" action="" method="post">
<input name="image" type="file" id="image" />
Upload
</form>
<div id="uploadresult"></div>
jQuery
javascript.js
function uploadimages(){
$.ajax({
type: 'POST',
url: '../ajax/upload.php',
processData: false,
contentType: false,
cache: false,
data: new FormData(this),
success: function (data) {
$("#uploadresult").html(data);
},
});
}
$("#uploadforms").click(function(){
uploadimages();
});
Php
Upload.php
<?php
if(!empty($_FILES['image'])) {
echo "Upload image";
}
else{
echo "Error";
}
?>
You forgot enctype='multipart/form-data' in your form
like this
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
For more info click here and here
Update:
Pass form from function call
$("#uploadforms").click(function(){
var form = $('form')[0]; //access form obj
uploadimages(form);
});
And access it in function as
function uploadimages(formObj){
$.ajax({
type: 'POST',
url: '../ajax/upload.php',
processData: false,
contentType: false,
cache: false,
data: new FormData(formObj), //changes here
success: function (data) {
$("#uploadresult").html(data);
},
});
}
I'm trying to POST the html input file to my PHP file, instead of using the traditional synchronous html forms.
The issue i'm facing is that i'm don't think im POST'ing the input file correctly to my PHP file because my PHP file is saying that its not receiving any POST data.
HTML:
<form id="uploadForm">
Begin by uploading a file (<5mb): <br> <br>
<span class="btn btn-info btn-file" id="buttonColor">
Browse... <span class="glyphicon glyphicon-folder-open"></span><input type="file" id="uploadBrowseBtn" name="uploadBrowseBtn" onchange='$("#upload-file-info").html($(this).val());'>
</span>
<br>
<span class='label label-info' id="upload-file-info">Choose a file.</span>
<br> <br>
<input type="button" class="btn btn-info" id="uploadSubmitBtn" value="Upload">
</form>
JS:
$("#uploadSubmitBtn").click( function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/upload.php',
data: formData,
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
},
})
});
PHP:
<?php
if(empty($_POST)){
echo true;
}else{
echo false;
}
?>
PHP puts posted files in the _FILE variable:
http://php.net/manual/en/reserved.variables.files.php
So even if the posting jquery part is working correctly, you could not see if a file was received by checking if the _POST variable is empty in PHP.
I'm not very good at jQuery, but this should do what you want.
$( document ).ready(function() {
$('#uploadSubmitBtn').on('click', function() {
var file_data = $('#uploadBrowseBtn').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#uploadForm').html(data);
}
});
});
});
<form id="uploadForm">
<input type="file" id="uploadBrowseBtn">
<input type="button" id="uploadSubmitBtn" value="Upload">
</form>
<?php
var_dump($_POST); // empty when received a file
var_dump($_FILES); // filled when received a file
?>
This question: jQuery AJAX file upload PHP answers your question, and has a perfect explanation to what it actually does.
I am having a problem with receiving File Data.
This is my HTML FORM:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Upload</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="General.js"></script>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="Form" action="upload.php">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="submit" type="submit" class="box" id="submit" value=" Upload "></td>
</tr>
</table>
</form>
As you can see it sends us to the file General.js
$(document).ready(function (e){
$("#Form").on('submit',(function(e){
e.preventDefault();
var formData = new FormData(document.getElementById('userfile'));
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "uploader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(callback){
alert(callback);
}
});
return false;
})
);
});
and the php page that need to recieve this:
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
Everything works fine, but the problem is when i send the data to the php file, it doesn't receive it as it should. Maybe i need to use some addition things?
Because the name of the file and the size and everything is empty.
EDIT:
$(document).ready(function(){
$("#submit").click(function(){
var formData = new FormData($('form')[0]);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "uploader.php",
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(callback){
alert(callback);
}
});
return false;
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
Also tried this code, but still it doesn't send the right information to the page. I am getting on the uploader.php page an error that says that the name of the file is empty, what means that maybe i don't receive it good or it didn't send at all.
Try using this...
$(document).ready(function (e) {
$("#Form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploader.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
console.log(data);
}
});
}));
});
change
var formData = new FormData(document.getElementById('Form'));
to
var fd = new FormData();
fd.append("userfile", document.getElementById('userfile').value);
I want to post a csv file to django view using jquery
<form id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>
js is:
function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
type: 'POST',
url:'/list/create/',
cache:false,
dataType:'json',
data:data,
success: function(result) {
console.log("ok")
}
});*/
}
django views.py:
def createlist(request):
if request.method == 'POST':
file = request.FILES
here not getting file.I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success.
Clearly i want that file in views.py by request.FILES
When uploading files, your form must have this attribute:
enctype='multipart/form-data'
like this:
<form id="form" enctype='multipart/form-data'>
This might help you understand.
You have to use a FormData object and a slightly modified version of basic ajax post:
var data = new FormData();
var file = null;
//when uploading a file take the file
$("#your-file-input-id").on("change", function(){
file = this.files[0]
});
//append the file in the data
data.append("file", file);
//append other data
data.append("message", "some content");
$.ajax({
url: '/path',
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function (data, status, xhr) {
//handle success },
error: function (data, status, xhr) {
//handle error
}
});
In Django you will find the file in request.FILES['file'].
I hope this is helpful.