Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
Related
A dropzone js need to create a new form but I want to use the same form to post both data and image, how can I achieve this, any idea.
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<!-- how to replace this field with dropzone but in this form in order to use the same ajax as below -->
<input type="file" name="photo" id="photo">
<button type="submit">send</button>
</form>
$("form").on('submit', function(e) {
$.ajax({
url: 'add.php',
type: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function(data) {
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
e.preventDefault();
});
You need to append dropzone files separately to FormData. Here is my solution,
$(document).ready(function () {
// get a reference to photo dropzone
var photoDropzone = Dropzone.forElement('#photo-dropzone');
$("form").submit(function (e) {
e.preventDefault();
// create the complete FormData here
var fd = new FormData(this);
// append dropzone files into the form data
for (var i = 0; i < photoDropzone.files.length; i++) {
fd.append('file[]', photoDropzone.files[i]);
}
$.ajax({
url: 'add.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function (data) {
console.log('done');
if (data.success == false) {
if (data.errors.name) {
$('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
}
if (data.errors.photo) {
$('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
}
}
});
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/basic.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// prevent auto processing in dropzone configuration
Dropzone.options.photoDropzone = {
autoProcessQueue: false
};
</script>
<form method="POST" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<button type="submit">send</button>
</form>
<!-- add dropzone form in the same page -->
<form action="add.php" class="dropzone" id="photo-dropzone">
I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'.
Thanks in advance.
Here's my Controller -
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$this->load->view('upload/upload');
}
public function upload_file() {
$config['upload_path'] = './uploads/Ajax/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
$title=$this->input->post('title');
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors()."<br>".$title;
}
else {
$data = $this->upload->data();
echo $data['file_name']." uploaded successfully";
}
}
}
/* end of file */
And here's the view
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX File Upload</title>
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js"> </script>
<script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"> </script>
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" autocomplete="off">
</p>
<p>
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile">
</p>
<input type="submit" name="submit" id="submit">
</form>
<h2>Result</h2>
<span id="result"></span>
</body>
I have tested in Firefox 43, IE11 & Chrome 43
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
secureuri :false,
fileElementId :'userfile',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
You need to add xhr function in ajax request
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
url: $(this).attr('action'),
data:formData,
cache:false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
you can use
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use
$('#form-id').ajaxSubmit({
// same config as ajax call but dont use data option right here
});
have a look on http://malsup.com/jquery/form/ to for more information about plugin
Use this
$("#upload-form").on('submit' ,function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: new FormData(form[0]),
dataType: 'json',
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function(data){
}
});
});
Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajaxFileUpload({
url :'./upload/upload_file/',
fileElementId : 'userfile', // your input file ID
dataType : 'json',
//
data : {
'title' : $('#title').val() // parse title input data
},
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
I am uploading files to a server, my code is running perfectly but i want to show progress bar till the image is being uploaded, i have seen various tutorials in core php but i want to accomplish it in codeigniter framework.
Below is my code:
<form name="posting_comment" id="posting_comment_<?=$row1['id']?>">
<input type="file" name="save_movie_<?=$row1['id']?>" id="movie_<?=$row1['id']?>" />
<input type="button" class="postbtn" id="submit_movie_<?=$row1['id']?>" value="Upload Video File" onclick = "return sendCareerData(<?=$row1['id']?>)"/>
</form>
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success:function(data)
{
console.log(data);
}
});
}
</script>
Controller:
public function do_upload()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName);
}
Use this before your success function
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$("#loading").html('Please wait....');
},
success:function(data)
{
console.log(data);
}
});
}
</script>
and in your view add
<div id="loading"></div>
Read this for more https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684
I am trying to write a code to upload images to my server. I have found one and it works.
This is the code
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="file" />
<button onclick="uploadFile();">Upload</button>
<script type="text/javascript">
function uploadFile() {
var input = document.getElementById("file");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
</script>
</body>
</html>
PHP:
<?php
$dir = "upload/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
?>
Now I have to put multiple form file inputs, so I tried doing the following:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="one" />
<button onclick="uploadFile1();">Upload</button>
<input type="file" id="two" />
<button onclick="uploadFile2();">Upload</button>
<script type="text/javascript">
function uploadFile1() {
var input = document.getElementById("#one");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
function uploadFile2() {
var input = document.getElementById("#two");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
</script>
</body>
</html>
But it doesn't work, I found that file type and id of the file form should be the same in order to make it work. What am I doing wrong here? How can I solve this problem?
You don't include the # when using getElementById (you're giving it an id value, not a CSS selector), so:
var input = document.getElementById("#one");
// Remove this ----------------------^
...and similarly for #two.
But you don't have to repeat the entire function just to use a different file input. Change your function to accept an id argument:
function uploadFile(id) {
var input = document.getElementById(id);
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
Then:
<button onclick="uploadFile('one');">Upload</button>
and
<button onclick="uploadFile('two');">Upload</button>
I want to upload a file asynchronously using jQuery - without using any PLUGIN.
JQuery is very new to me and after looking at various forums I ended up with this code :
HTML:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#myform').submit(function() {
var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
type: "POST",
url: "upload.php",
data: formData,
processData: false,
contentType: 'multipart/form-data',
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
success:function(msg){
//alert( "Data Uploaded: " + msg );
document.getElementById('display').innerHTML = msg;
}
});
return false;
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" id="myform" name="myform" method="POST">
<input name="file" type="file" id="file" name="file"/>
<input type="text" name="txtValue" value="" id="txtValue">-->
<input type="submit" value="Upload" id="button" name="button"/>
<div id="display"></div>
</form>
</body>
</html>
PHP:
<?php
$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
$value = "success";
}
else {
$value = "error";
}
echo $value;
?>
This code is not working and everytime the "display" DIV is printing "error". Please help me out.
Take a hidden div. Inside that div take a iframe and set the form's target to the iframe's id.
In jQuery. In after document ready function add a load event handler (say LEH)to the iframe.
So that when the form is submitted and file is uploaded and iframe is loaded then the LEH will get called
This will act like success event.
Note: you need to make minor tweaks as for the first time when the page is loaded then also the iframe is loaded. So there will be a first time check also.
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
You can do some validation if you want.
$(':file').change(function(){
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
//Your validation
});
Now the Ajax submit with the button's click:
$(':button').click(function(){
var formData = new FormData($('form')[0]);
$.ajax({
url: 'upload.php', //Server script to process data
type: 'POST',
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;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
Now if you want to handle the progress.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
SOURCE
You can use following plugins to upload files using ajax:
jQuery Form Plugin
Uploadify
The plugin in the first link provides some very useful callbacks. You can check the documentation at the given link.
I have user Jquery Form Plugin in my project.
JQuery the raw xhr object is wrapped in jqXhr Object which doesn't have any reference to the new upload property of the xhr.
Hope you can start with this below example.
html:
<input type="file" class="text-input" size="50" id="file_upload" value="" name="file_upload"/>
var formData = new FormData($('form')[0]);
$.ajax({
url: '/files/add_file', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
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;
},
dataType: 'JSON',
beforeSend: beforeSendHandler,
success: function(data) {
if (data.error){
showMessage(data.html, false, false);
}
else{
showMessage(data.html, false, false);
setTimeout("window.location = 'path/to/after/uploading';",450)
}
},
error: function(data) {
showMessage(data.html, false, false);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});