Image file coming empty - php

I have created a script to upload the image with text but the problem is that when we post the data and upload the image the file is coming empty I do not know why the file is coming empty can anyone help me out to get the correct file
This is my ajax script
$(document).ready(function(e) {
$("#post").on('submit', (function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
alert(formData);
formData.append('post_dt', $("#contentbox").html());
$.ajax({
url : "http://domainname.com/demo/forums/post_forum",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
$("#contentbox").empty();
form.reset();
},
complete: function() {
$("#load").hide();
}
});
}));
});
This the html form which is being created
<form method="POST" action="" id="post" enctype="multipart/form-data" onsubmit="return false;">
<ul>
<li>
<i class="fa fa-photo"></i> Upload A Photo / Document
<input type="file" name="image" />
</li>
</ul>
<div id='display'></div>
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
My php script which I have created within the controller
public function post_forum() {
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$this->load->library('upload', $config);
if(!empty($this->input->post('image'))) {
if (!$this->upload->do_upload('image')) {
$error = array('error' => $this->upload->display_errors());
} else {
$dt = $this->upload->data();
$file = $dt['file_name'];
}
} else {
$file = 'Filename.jpg';
}
$word_dta = $this->input->post('post_dt');
$time_posted = time();
$user_id = $this->basic_model->is_login($this);
$data_upload = array(
'upload_document' => $file,
'discussion' => $word_dta,
'user_id' => $user_id,
'time_posted' => $time_posted,
'status' => 'Posted'
);
$post_id = $this->basic_model->insertRecord($data_upload, 'forums');
$data = array(
'file_name' => $file,
'data' => $word_dta,
'time_posted' => $time_posted,
'post_id' => $post_id,
'name' => $this->basic_model->getUserData(),
'command' => 'Submit Post'
);
$this->load->view('forum/includes/get_data', $data);
}

add id as imageFieldId to file in html. Then try
var file_data = $('#imageFieldId').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
//formData.append('post_dt', $("#contentbox").html());
$.ajax({.....

I have sorted out my issue I was making a mistake within the controller which was my mistak so I have resolved my issues take care

Ensure your webserver (nginx/apache) upload size limit are correct.
This link could be your reference to set the upload size:
Increase File Upload Size Limit
Edit NginX Conf to Increase File Size Upload

Related

File upload with form inputs AJAX not working

I've been searching for solutions across SO and have tried them, but not one of the answers I found has solved my problem. So here is it.
I am working on a simple web app with input details and file upload (.docx files). I used FormData for the handling of form data, but the server-side operation only works for the form inputs like text, password, date ,etc.
This is my JS code; the commented lines are the one which I attempted but did not work.
var myForm = $("#add-thesis-form");
var formData = new FormData(myForm);
//var formData = myForm.serialize();
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: formData
// processData: false,
// contentType: false
}).done(function(data){
$('#addThesisModal').modal('hide');
alert(data);
//alert("Successfully saved a record to the database. ");
showThesis();
});
My PHP code (using Meekro DB)
$title = $_POST["title"];
$description = $_POST["description"];
$categoryId = $_POST["category_id"];
$collegeId = $_POST["college_id"];
$departmentId = $_POST["department_id"];
$uploadedBy = $_SESSION["user"];
$uploadedAt = DB::queryFirstField("SELECT NOW();");
$year = $_POST["thesis_year"];
$keywords = $_POST["keywords"];
$authors = $_POST["authors"];
//FILE UPLOAD
$targ_dir = "../uploads/";
$targ_file = $targ_dir . basename($_FILES["thesis"]["name"]);
$flagOk = 1;
$tempFolder = $_FILES["thesis"]["tmp_name"];
move_uploaded_file($tempFolder, $targ_file);
//!FILE UPLOAD
$result = DB::insert('theses', array(
"title" => $title,
"description" => $description,
"categoryId" => $categoryId,
"collegeId" => $collegeId,
"departmentId" => $departmentId,
"uploadedBy" => $uploadedBy,
"uploadedAt" => $uploadedAt,
"pubyear" => $year,
"filepath" => $targ_file,
"views" => 0,
"rating" => 0,
"keywords" => $keywords,
"authors" => $authors
));
I've tried a print_r($_FILES) and that one works, but this one doesn't. Please help me. Thanks.
Setting the contentType:false causes the server to throw an error Undefined index on all the $_POST variables.
Maybe your form should includes enctype="multipart/form-data"
Maybe this would work :
$.ajax({
type: "POST" ,
url: "thesis-scripts/add_thesis.php",
data: "multipart/form-data"
...

Php Ajax posting multiple datas

var name = $("#name").val();
$.ajax({
type: "post",
dataType: "json",
url: "save.php",
data: {
image: canvas.toDataURL(),
name:name
}
});
I'm trying to save my cropped image with name from get text field.
When I sent only imageurl its working. How can I fix this problem ?
save.php:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// location to save cropped image,
$ad=$_POST['name'];
$url = 'temp/"'.$ad.'".jpg';
//$url = 'temp/one.jpg';
// remove the base64 part
$base64 = preg_replace('#^data:image/[^;]+;base64,#', '', $_POST['image']);
$base64 = base64_decode($base64);
$source = imagecreatefromstring($base64); // create
imagejpeg($source, $url, 100); // save image
// return URL
$validation = array (
'url' => $url);
echo json_encode($validation);
}

How to process with RubaXa File API uploaded file blobs in php?

I found this useful tool called RubaXa / jquery.fileapi
which slices a file and create blobs. But within the documentation there is a lack of information about how to process the uploaded parts on the server. The example on the page refers to a url: './ctrl.php' but you can't see the content of it on the developers page. I used this (look below) client side script so far and there were no errors. A file was sliced and several post requests appeared in my firebug console. So it seems to work. But how to process the received fileparts in PHP on the server?
imported scripts:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script>
window.FileAPI = {
debug: false // debug mode
, staticPath: 'jquery.fileapi-master/FileAPI/' // path to *.swf
};
</script>
<script src="jquery.fileapi-master/FileAPI/FileAPI.min.js"></script>
<script src="jquery.fileapi-master/jquery.fileapi.min.js"></script>
the initiation and setup of the fileuploader:
jQuery(function ($){
$('#uploader').fileapi({
url: 'stash.php',
autoUpload: true,
accept: 'video/*',
multiple: false, //only single file upload
chunkSize: .5 * FileAPI.MB //filesize of the blobs/chunks
});
});
the HTML file upload "form":
<div id="uploader">
<div class="js-fileapi-wrapper">
<input type="file" name="files[]" />
</div>
<div data-fileapi="active.show" class="progress">
<div data-fileapi="progress" class="progress__bar"></div>
</div>
</div>
Hope this code will help you
<?php
/**
* FileAPI upload controller (example)
*/
include './FileAPI.class.php';
if( !empty($_SERVER['HTTP_ORIGIN']) ){
// Enable CORS
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type');
}
if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ){
exit;
}
if( strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' ){
$files = FileAPI::getFiles(); // Retrieve File List
$images = array();
// Fetch all image-info from files list
fetchImages($files, $images);
// JSONP callback name
$jsonp = isset($_REQUEST['callback']) ? trim($_REQUEST['callback']) : null;
// JSON-data for server response
$json = array(
'images' => $images
, 'data' => array('_REQUEST' => $_REQUEST, '_FILES' => $files)
);
// Server response: "HTTP/1.1 200 OK"
FileAPI::makeResponse(array(
'status' => FileAPI::OK
, 'statusText' => 'OK'
, 'body' => $json
), $jsonp);
exit;
}
function fetchImages($files, &$images, $name = 'file'){
if( isset($files['tmp_name']) ){
$filename = $files['tmp_name'];
list($mime) = explode(';', #mime_content_type($filename));
if( strpos($mime, 'image') !== false ){
$size = getimagesize($filename);
$base64 = base64_encode(file_get_contents($filename));
$images[$name] = array(
'width' => $size[0]
, 'height' => $size[1]
, 'mime' => $mime
, 'size' => filesize($filename)
, 'dataURL' => 'data:'. $mime .';base64,'. $base64
);
}
}
else {
foreach( $files as $name => $file ){
fetchImages($file, $images, $name);
}
}
}
?>
you can get the source code in here:
https://github.com/mailru/FileAPI
inside the "server" folder it is the ctrl.php and FileAPI.class.php

Ajax Upload with JQuery and PHP

I have a problem with Ajax uploading using Jquery and PHP.. Although there're many stackoverflow posts discussing the same subject, I didn't find one that matches my case.
HTML :
<form action="uploadrecord.php" id="upload_record_form" method="post" enctype="multipart/form-data">
<div id="upload_record_form_result"></div>
<ul>
<li><input type="file" name="uploadrecord" id="uploadrecord"/></li>
</ul>
<progress></progress>
</form>
</div>
Javascript :
$('#uploadrecord').live('change', function(event) {
var formData = new FormData($('#upload_record_form')[0]);
$.ajax({
url: $('#upload_record_form').attr('action'),
type: 'POST',
enctype: 'multipart/form-data',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: completeHandler = function(data) {
$('#upload_record_form_result').html(data);
},
error: errorHandler = function() {
alert("Failure");
},
data: formData,
cache: false,
contentType: false,
processData: false
}, 'json');
});
PHP
<?php
if (isset($_FILES['uploadrecord'])) {
if ((!empty($_FILES["uploadrecord"])) && ($_FILES['uploadrecord']['error'] == 0)) {
$filename = basename($_FILES['uploadrecord']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
$types = array(
'video/mp4', 'video/3gpp', 'video/divx', 'video/flv', 'video/mpeg', 'video/mpeg-2', 'video/mpeg4', 'video/mpeg4'
);
$type = $_FILES['uploadrecord']['type'];
if (in_array($type, $types) && $_FILES["uploadrecord"]["size"] < 20000000) {
$new = sha1(date('Y/m/d H:i:s'));
$newname = dirname(__FILE__) . '/records/' . $new . '.' . $ext;
if ((move_uploaded_file($_FILES['uploadrecord']['tmp_name'], $newname))) {
echo 'done';
} else {
echo 'failed 1';
}
}
} else {
echo 'failed 2';
}
} else {
echo 'Upload failed 3';
}
When I try the previous code, and upload a record file, it displays "failed 2", meaning that the "error" code is different from 0.
when I var_dump the array $_FILES['uploadrecord']...this is what I get:
array (size=5)
'name' => string 'Nao Robot.flv' (length=13)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 1
'size' => int 0
I can't figure out, why 'tmp_name' and type are set to empty strings, and why the size is set to 0.
Where's the problem exactly? is it from the client or server side scripting?
Thanks in advance
ON MAC OSX:
1) Go to /etc/php.ini
2) Open the file with permission to write/read
3) Search for line:
upload_max_filesize = 2M
4)Change to, for example, 6MB ou more:
upload_max_filesize = 6M
5) Save and restart apache with command:
sudo apachectl restart

Codeigniter multiple upload of different file-types

I want to upload an audio file and an image in the same form and store their names in the db...what happens is only one of the files is uploaded (the one that is first in row)
the other gives an error of not allowed type
here is my view:
<?php echo form_open_multipart('index.php/ena_dyo_edit');?>
Title:<input type='text' name="title" size="40" id="title" />
<p>Title Photo:<input type="file" name="title_photo" size="20" id="title_photo" /></p>
<p>Body:<textarea name="body" rows = "10" cols="60" id="body"></textarea><p>
<p>Soundfile:<input type="file" name="soundfile" size="20" id="soundfile" /></p>
<p>Author:<input type="text" name="author" size="40" id="author"/></p>
<p><input type="submit" value="Submit New Post"/></p>
<?php echo form_close(); ?>
and here are my model functions:
function soundfile_upload($userfile = 'userfile'){
//uploads a sound file
$config = array(
'upload_path' => './uploads/soundfiles/',
'allowed_types' => 'mp3|wav|aif|aiff|ogg',
'max_size' => '256000' //250 MB max size
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload($userfile)) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_error', $error);
}
else{
$soundfile_data = $this->upload->data();
$entry_title = $this->input->post('title'); //using the name of the post to relate the audio file
$entry_id = $this->db->insert_id(); //the id of our last entry!
//create array to load to database
$insert_data = array(
'soundfile' => $soundfile_data['file_name']
);
//$this->db->where('id', $entry_id);
$this->db->update('entries', $insert_data,array('id' => $entry_id)); //load array to database
}
}
function title_photo_upload($userfile = 'userfile'){
//uploads a photo for a post title
$config = array(
'upload_path' => './uploads/title_photos/',
'allowed_types' => 'jpg|jpeg|gif|png',
'max_size' => '256000' //250 MB max size
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload($userfile)) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_error', $error);
}
else{
$soundfile_data = $this->upload->data();
$entry_id = $this->db->insert_id(); //the id of our last entry!
//create array to load to database
$insert_data = array(
'title_photo' => $soundfile_data['file_name']
);
$this->db->update('entries', $insert_data,array('id' => $entry_id)); //load picture where id = entry_id
}
}
According to the CI docs, the 'allowed_types' portion of the config is a pipe delimited list of mime types, not file extensions. It looks to me like you're using the file extensions which would probably produce an error of not allowed type if the extension isn't the same as the mime type. For example, my mp3 files tend to have the mime type 'audio/mpeg'. So your allowed_types config should look like this:
'allowed_types' => 'audo/mpeg|audio/x-wav|audio/x-aiff|application/ogg'

Categories