Im looking for help here. Cant figure it out where is problem here. Im trying to make multiple file upload to database using Ajax and PHP. I am getting this error:
Warning: file_get_contents(iamge.png): failed to open stream: No such
file or directory in /var/www/html/includes/forms/addProductSteps/BTR/upload.php on line 12
Can you please check code below:
index.php:
<form id="fourthStepForm" class="" action="" method="post" enctype="multipart/form-data">
<input type="file" multiple id="imagesToUpload" name="files[]" value="">
<div class="col-xs-3 col-md-3"><input type="submit" onclick="fourthStep();return false" name="submit" value="Finalize" class="btn btn-primary btn-block btn-md" tabindex="5"></div>
</form>
function fourthStep(){
var formData = new FormData();
var ins = document.getElementById('imagesToUpload').files.length;
for (var x = 0; x < ins; x++) {
formData.append("files[]",
document.getElementById('imagesToUpload').files[x]);
}
$.ajax({
url: 'includes/forms/addProductSteps/BTR/upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
}
upload.php:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include_once'../../../connections_multi.php';
$p_id = 1001; //for testing purpose
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
$file = addslashes(file_get_contents($_FILES["files"]["name"][$i]));
if (!($stmt = $db->prepare("INSERT INTO products.battery_lobs ( p_id,img) VALUES (?,?)"))) {
$response = $stmt->error;
}
if (!$stmt->bind_param("sb", $p_id, $file )) {
$response = $stmt->error;
}
if (!$stmt->execute()) {
$response = $stmt->error;
}else{
$response = "true";
}
}
}
echo $response;
and $response i get here is "true". So data is inserted but BLOB is 0 bytes. No image.
Thanks!
Problem is in your upload.php file.
This line:
$file = addslashes(file_get_contents($_FILES["files"]["name"][$i]));
You need change it like this:
$file = addslashes(file_get_contents($_FILES["files"]["tmp_name"][$i]));
Then you upload file, file is saved in temporary directory and using random name, you can get it used $_FILES["files"]["tmp_name"].
Related
Hi I have a modal to upload multiple images as shown below and would like to upload the images and return back the error message or a successful message. The problem is I cannot seem to process all images.I have created a formdata in the javascript where I am appending all files but from the php I seem not to be able to handle all of them. Any idea why?
<!-- Modal -->
<div class="modal fade" id="uploadImages" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload Scanned Images</h4>
</div>
<div class="modal-body" id="body">
<form method="POST" enctype="multipart/form-data">
Select file : <input type='file' name='file[]' id='file' class='form-control' multiple=""><br>
<input type='submit' class="btn btn-info" value="Upload File" id='but_upload' name='submit'>
</form>
<script src="uploadImages.js"></script>
</div>
<div class="modal-footer">
<p>Only jpeg, png, bmp and tiff Images are allowed to be uploaded</p>
</div>
</div>
</div>
</div>
I also have a javascript to send an ajax post:
$(document).ready(function () {
$("#but_upload").click(function () {
var filedata = $('#file')[0];
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0,
len = filedata.files.length,
img, reader, file;
for (i = 0; i < len; i++) {
file = filedata.files[i];
if (formdata) {
formdata.append("file", file);
}
}
$.ajax({
url: 'uploadImages3.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
success: function (response) {
alert(response);
},
});
});
});
and this is my php file
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "SavedImages/" . $filename;
$uploadOk = "No Errors";
$imageFileType = pathinfo($location, PATHINFO_EXTENSION);
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'tiff'];
$all_files = count($_FILES['file']['name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['file']['name'][$i];
$file_tmp = $_FILES['file']['tmp_name'][$i];
$file_type = $_FILES['file']['type'][$i];
$file_size = $_FILES['file']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['file']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$uploadOk = $uploadOk . 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$uploadOk = $uploadOk . 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (file_exists($file)) {
$uploadOk = $uploadOk . 'File already exists: ' . $file_name . ' ' . $file_type;
}
if ($uploadOk != "No Errors") {
echo $uploadOk;
} else {
/* Upload file */
if (move_uploaded_file($_FILES['file']['tmp_name'], $location)) {
echo "File saved";
} else {
echo $uploadOk;
}
}
}
You have:
formdata.append("file", file);
When working with PHP, if you have multiple form fields with the same name, that name must end in [] or only one of them will be available.
Looping over the files manually in the JS is pointlessly overcomplicated though.
Bind the event handler to the submit event of the form
Use the form to populate the FormData object
You also need to prevent the default behaviour - at the moment you are running your JS when the submit button is clicked, but the normal form submission is going to continue and load a new page (killing the JS program as it goes).
Such:
$("form").on("submit", function(e) {
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: 'uploadImages3.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
success: function(response) {
alert(response);
},
});
});
Then your PHP will have an array of files, each of which will have name, etc. It won't have a file, containing an array of names etc.
$_FILES['file']['name'][$i]; should be $_FILES['file'][$i]['name']; and your count method is wrong too.
It's easier to work with a foreach loop though:
foreach ($_FILES['file'] as $file) {
$file_name = $file['name'];
# etc
}
I found a solution on internet on how to upload multiple files using ajax and php. In ajax request, I am passing form with files selected to upload, but I need to add one more parameter, but when I am doing it, it is not working. Im not good at php, and I tried pass second parameter in many ways but none worked. How can I pass second parameter so everything will be still working?
html:
<form method="post" enctype="multipart/form-data">
Select files to upload:
<input name="file[]" type="file" multiple>
<input type="button" onclick="upload(this)" value="Upload"/>
</form>
javascript:
function upload(element) {
var formData = new FormData($(element).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
success: function (callback) {
// some code
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
php
<?php
$mysqli = include 'connection.php';
$total = count($_FILES['file']['name']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
for ($i = 0; $i < $total; $i++) {
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
$location = 'uploads/';
$target_file = $location . basename($name);
if (isset($name)) {
if (empty($name)) {
echo 'Please choose a file' . "\n";
} else if (file_exists($target_file)) {
echo 'File already exists.' . "\n";
} else if ($size > 1000000) {
echo 'File is too large' . "\n";
} else {
$tmp_name = $_FILES['file']['tmp_name'][$i];
$statement = $mysqli->prepare("INSERT INTO files (name, subjectId) VALUES (?, ?)");
$str = '1'; // here I would like to set variable using $_POST
$statement->bind_param('ss', $name, $str);
if (move_uploaded_file($tmp_name, $location . $name)) {
if ($statement->execute()) {
echo 'File successfully uploaded :' . $location . $name . "\n";
} else {
echo 'Error while executing sql' . "\n";
}
} else {
echo 'Error while uploading file on server' . "\n";
}
}
}
}
}
So what I would like to get is in javascript add second parameter:
data: formData, mySecondParameter
and then in php when I am binding params for sql, I would like to input there variable that I passed from javascript:
$str = $_POST['contentOfMySecondParameter'];
You can use FormData.append() to add more parameters.
var formData = new FormData($(element).parents('form')[0]);
formData.append('mySecondParameter', contentOfMySecondParameter);
Then use $_POST['mySecondParameter'] in PHP to get this parameter.
Easiest way to do it, add
<input type='hidden' name='contentOfMySecondParameter' value='???' />
to html. You will get $_POST['contentOfMySecondParameter'] in php.
Only one object can be passed there. If you want another variable just append it to formData like this:
var formData = new FormData($(element).parents('form')[0]);
formData.append("mySecondParameter", mySecondParameter);
$.ajax({
...
data: formData,
...
I am not able to upload multiple images in a folder in codeigniter. I have used this reference Multiple image upload. Someone please help me. Atleast the author of this reference please help me to sort out this problem. Here is my code
View
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
Script
$(document).ready(function(){
$('#save').on('click', function(){
var fileInputs = $('.file_input');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 ){
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
}
});
$.ajax({
url: '<?php echo base_url(); ?>exerciseset/process',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
method: 'post',
success: function(response){
console.log(response);
}
});
});
});
Controller
public function process()
{
$fileuploadurl = base_url() . "study_set/";
$config['upload_path'] = 'study_set/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp|mp3|mp4';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '25000000';
$F = array();
$count_uploaded_files = count( $_FILES['images']['name'] );
$files = $_FILES;
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES['userfile'] = [$files['images']['name'][$i]];
$F[] = $_FILES['userfile'];
// Here is where you do your CodeIgniter upload ...
$this->load->library('upload', $config);
$this->upload->data($_FILES['userfile']);
if (!$this->upload->data('images')) {
echo $this->upload->display_errors();
}
}
echo json_encode($F);
}
It returns the images name into array but not able to upload it into folder. And also i need each image name in separate variable. Please help me i am in hurry.
In your code it seems like you missed to upload file. Hence it will not moved to specific folder. Please check below, Hope it will help you.
public function process()
{
$fileuploadurl = base_url() . "study_set/";
$config['upload_path'] = APPPATH . 'uploads/study_set/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp|mp3|mp4';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '25000000';
$F = array();
$count_uploaded_files = count( $_FILES['images']);
$result = array();
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES["file"]["name"] = $_FILES["images"]["name"][$i];
$_FILES["file"]["type"] = $_FILES["images"]["type"][$i];
$_FILES["file"]["tmp_name"] = $_FILES["images"]["tmp_name"][$i];
$_FILES["file"]["error"] = $_FILES["images"]["error"][$i];
$_FILES["file"]["size"] = $_FILES["images"]["size"][$i];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$result['errors'][] = $this->upload->display_errors();
}else{
$result['success'][] = $this->upload->data();
}
}
echo json_encode($result);
}
Please make sure you have specified correct folder path and folder has enough permissions to write files.
Let me know if it not works.
So I've been developing a plugin for WordPress.
As I already have made an application which uploads files for me, I thought it would be easy but alas, I can't think of what I am doing wrong.
The problem is; my $_FILES['image'] is not set.
Can anyone tell me what is wrong with my code, because I can't find out what it is.
Form
<form action="" method="POST" enctype="multipart/form-data">
<table class="table ws-form-table">
<tbody>
<tr>
<td>
Add Text:
</td>
<td>
<input type="text" id="ws-text">
</td>
<td>
<button type="button" class="btn btn-primary ws-add-text ws-add-button">+</button>
</td>
</tr>
<tr>
<td>
Add Image:
</td>
<td>
<input type="file" name="image"><progress></progress>
</td>
<td>
<button type="button" class="btn btn-primary ws-add-image ws-add-button">+</button>
</td>
</tr>
</tbody>
</table>
<div class="preview-container">
<div class="preview-strict">
<img class="ws-image" src="<?php echo $feat_image; ?>" alt="" style="width: 300px; height: 300px;">
</div>
</div>
</form>
JS
jQuery('.ws-add-image').click(function() {
var formData = new FormData(jQuery('form')[0]);
console.log('Click Initiated');
console.log('Ajax Try...');
jQuery.ajax({
url: '../../wp-content/plugins/my-plugin/my-plugin-handler.php',
type: 'POST',
xhr: function() {
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false,
error: function() {
console.log('Error Initiated');
},
}).done(function() {
alert('dsa');
jQuery('.preview-strict').prepend('<div id="dragHelper" style="display:inline-block; z-index: 999; cursor: move;"><img id="theImg" src="../../wp-content/plugins/my-plugin/images/' + readCookie('image') + '" width="200px" height=200px; /></div>');
jQuery("#dragHelper").draggable({drag: function(){
var offset = jQuery(this).offset();
var xPos = offset.left;
var yPos = offset.top;
jQuery('#posX').text('x: ' + xPos);
jQuery('#posY').text('y: ' + yPos);
}
});
jQuery("#theImg").resizable();
});
alert(readCookie('image'));
console.log('Done!');
});
function progressHandlingFunction(e){
if(e.lengthComputable){
jQuery('progress').attr({value:e.loaded,max:e.total});
}
}
PHP
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include_once($_SERVER['DOCUMENT_ROOT'].'/test/wp-load.php' );
global $wpdb;
$table_name = $wpdb->prefix . "my-plugin";
if(isset($_FILES['image'])) {
$wty = 'ISSET';
$sql = $wpdb->get_results("SELECT ID FROM " . $table_name . " ORDER BY ID DESC LIMIT 1");
echo $_FILES['image']['name'];
foreach( $wpdb->get_results("SELECT ID FROM " . $table_name . " ORDER BY ID DESC LIMIT 1") as $key => $row) {
$id = $row->ID;
}
$temp = explode(".", $_FILES["image"]["name"]);
$last = $id . round(microtime(true)) . '.' . end($temp);
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
$file_type = $_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$ext = end((explode(".", $file_name)));
$expensions= array("jpeg","jpg","png");
if(empty($errors)==true) {
move_uploaded_file($file_tmp, ABSPATH . "test/wp-content/plugins/my-plugin/images/" . $last);
}
else
{
print_r($errors);
}
}
$cookie_name = "image";
$cookie_value = $wty;
$cookie_exp = time() + (86400 * 30);
setcookie($cookie_name, $cookie_value, $cookie_exp, "/");
?>
So this is how it works: Image gets chosen, button gets clicked, click event runs, ajax runs a PHP file. The PHP file (needs to) upload image, creates cookie with image name. Image name gets pulled from cookie, and adds it to the DOM after ajax done.
I've tried to look this up but for some reason I can't find anything but peoples saying that I might be forgetting enctype="multipart/form-data".
So what am I doing wrong?
Keep in mind that this is a WordPress plugin. So it may be something WordPress related. But I don't think so.
I'm still learning so any help with improving the code is appreciated!
This code will work for single or multiple files.
$('.ws-add-image').click(function() {
var data = new FormData();
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "my_path",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
alert(msg);
}
});
});
Then in your php file you will get file using..
$_FILES['file-0']
$_FILES['file-1']
You are missing following while cooking up your AJAX request:
formData.append('image', $('input[type=file]')[0].files[0]);
Basically, I want my user to fill some input form and upload a lot image file in one form. Here is the little piece of the code.
<?php echo form_open_multipart('', array('id' => 'upload', 'enctype' => "multipart/form-data")); ?>
<div class="form-group col-sm-3 col-md-4">
<label for="last5">Last 5 Test</label>
<input type="text" name="last5" id="last5" class="form-control" />
</div>
<div class="form-group col-sm-3 col-md-4">
<label for="cert5">Certified By</label>
<input type="text" name="cert5" id="cert5" class="form-control" />
</div>
<div class="form-group col-sm-3 col-md-2">
<label for="driver">Driver</label>
<input type="text" name="driver" id="driver" class="form-control" />
</div>
/*This is for upload file*/
<div class="form-group col-sm-12">
<label for="file">Upload Foto</label>
<input name="file[]" id="file" type="file" multiple >
</div>
<div class="form-group col-sm-6 col-md-6 ">
<button type="submit" class="btn btn-primary btn-block">Update & Submit</button>
</div>
<div class="form-group col-sm-6 col-md-6">
<button type="reset" class="btn btn-default btn-block">Reset</button>
</div>
<?php echo form_close(); ?>
I use php codeigniter on side server. Now, to submit those data, I use AJAX twice, first, I want make sure the common input is success then upload those file on next.
So, I declare those file input :
$("#file").fileinput({
dropZoneEnabled : false,
showUpload : false,
uploadUrl: "http://localhost/depo/", // Please, triggered upload
uploadAsync: false,
maxFileCount: 10
});
And here is the AJAX :
$(document).on('submit', '#upload', function (e) {
e.preventDefault();
$('#no_surat').prop("disabled", false);
var form = $('#upload');
var inputFile = $('input#file');
var filesToUpload = inputFile[0].files;
// make sure there is file(s) to upload
if (filesToUpload.length > 0) {
// provide the form data that would be sent to sever through ajax
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
$.ajax({ //Upload common input
url: "<?php echo base_url('surveyor/c_surveyor_inspection/update_by_inspection_surveyor_2'); ?>",
type: "POST",
data: form.serialize(),
dataType: 'json',
success: function (response) {
if (response.Status === 1) {
$.ajax({ //Then upload the foto
url: "<?php echo base_url('surveyor/c_surveyor/add_file_image/'); ?>/" + response.Nama_file + '/' + response.No_surat,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (obj) {
$('#no_surat').prop("disabled", true);
console.log("The photos is successfully upload");
}, fail: function () {
console.log('Error');
}
});
}
}
});
} else {
$('#file').after('<div class="callout callout-danger lead" id="div_error"><p id="pesan_error"></p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html("Harap sertakan foto...");
$('#div_error').fadeOut(7000);
}
return false;
});
This is the code to handling image upload:
public function add_file_image() {
$last = $this->uri->total_segments();
$id = $this->uri->segment($last);
echo urldecode($this->uri->segment($last));
$pathToUpload = "D:\Foto\ " . $this->uri->segment(4, 0) . '-' . $this->uri->segment(5, 0);
if (!is_dir($pathToUpload)) {
mkdir($pathToUpload, 0755, true);
mkdir($pathToUpload . '\thumbs', 0755, true);
}
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir($pathToUpload)) {
mkdir($pathToUpload, 0755, true);
mkdir($pathToUpload . '\thumbs', 0755, true);
$dir_exist = false; // dir not exist
}
if (!empty($_FILES)) {
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $id;
$config['overwrite'] = FALSE;
//$config['encrypt_name'] = TRUE;
$this->load->library('upload');
$files = $_FILES;
$number_of_files = count($_FILES['file']['name']);
$errors = 0;
$upload_array = array();
// codeigniter upload just support one fileto upload. so we need a litte trick
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['file']['name'] = $files['file']['name'][$i];
$_FILES['file']['type'] = $files['file']['type'][$i];
$_FILES['file']['tmp_name'] = $files['file']['tmp_name'][$i];
$_FILES['file']['error'] = $files['file']['error'][$i];
$_FILES['file']['size'] = $files['file']['size'][$i];
// we have to initialize before upload
$config['file_name'] = $this->uri->segment(4, 0) . '-' . $this->uri->segment(5, 0) . '-' . $i;
// UPLOAD EKSEKUSI
$this->upload->initialize($config);
if (!$this->upload->do_upload("file")) {
$errors++;
echo $this->upload->display_errors();
} else {
$upload_data = $this->upload->data();
print_r($upload_data);
$new_upload = array(
"NO_INSPECTION" => $id,
"file_name" => $upload_data['file_name'],
"file_orig_name" => $upload_data['orig_name'],
"file_path" => $upload_data['full_path']
);
$this->load->library('image_lib');
$resize_conf = array(
'source_image' => $upload_data['full_path'],
'new_image' => $upload_data['file_path'] . '\thumbs\thumb_' . $upload_data['file_name'],
'width' => 200,
'height' => 200
);
//use first config
$this->image_lib->initialize($resize_conf);
//run resize
if (!$this->image_lib->resize()) {
echo "Failed." . $this->image_lib->display_errors();
}
//clear
$this->image_lib->clear();
//initialize second config
$this->image_lib->initialize($resize_conf);
//run resize
if (!$this->image_lib->resize()) {
echo "Failed." . $this->image_lib->display_errors();
}
//clear
$this->image_lib->clear();
//push all informatin to array for insert batch
array_push($upload_array, $new_upload);
}
}
//Insert batch codeingter
$this->m_surveyor->save_files_info($upload_array);
if ($errors > 0) {
echo $errors . "File(s) cannot be uploaded";
}
} elseif ($this->input->post('file_to_remove')) {
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/uploads/" . $file_to_remove);
} else {
$this->listFiles();
}
}
I have case like this :
1. User choose a or lot of file images on first chance, e-g 2 files image.
2. After loaded, user choose a file again
3. But, the image that was successfully upload just one last file chosen. The two files in not uploaded ?
In my controller, I use insert batch. So i must to save all information into database in array(array(),array());
Is it possible to upload those file like triggered ? So, if user choose two files and then choose again another file, so on so on, all the choosed file will be uploaded.