in my laravel application I am using dropzone programmatically to upload images. this is my Controller to store images in VehicleController
$photos = $request->file('file');
dd($photos);
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();//this is line 75
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = new Upload();
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->save();
}
return Response::json([
'message' => 'Image saved Successfully'
], 200);
and programatically jquery is
Dropzone.autoDiscover = false;
// Dropzone class:
var myDropzone = new Dropzone("div#my-dropzone", { url: '/form'});
routes
Route::post('form','VehicleController#store');
My blade file is
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input type="file" name="file" multiple>
</div>
</div>
but when my form submit button clicked following errors occurred,
1/1) FatalErrorException
Call to a member function getClientOriginalExtension() on null
in VehicleController.php line 75
when I use dd(photos); on
$photos = $request->file('file');
result comming in 'null' massage then, how can fix this problem?
Please try using below AJAX Code.
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
Remove the Action(action="{{url('form')}}") from your form Tag.
var datastring = $('#fromid').serialize();
$.ajax({
url: "controller url",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: datastring,
success: function(data){
if(data == '100'){
if($('#file').val() != ''){
var form = $('#fromid')[0];
var formData = new FormData(form);
var imageurl='controller image upload url';
$.ajax({
url:imageurl,
type:"post",
data:formData,
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
setTimeout(function(){
window.location.href="redirect url";
},4000);
}
});
}else{
setTimeout(function(){
window.location.href="redirct url";
},4000);
}
}else{
alert(data);
}
}
});
-------- Controller code.
Print_r($_FILES); //You got the result.
Need to add enctype attribute as:
<form action="" method="post" enctype="multipart/form-data">input here</form>
Please add enctype="multipart/form-data" in form. Like this:
<form action="" method="post" enctype="multipart/form-data">
Related
I am trying to insert file and text to database using ajax but it is not working.
the main problem is file which is not inserting in database
Here is my code
<form id="descriptionsubmit" enctype = "multipart/form-data">
<textarea class="form-control" id="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="submit" class="update-btn">Next</button>
</form>
Ajax for same
the alert(data)is showing nothing
$(function(){
$('form#descriptionsubmit').on('submit', function (e) {
e.preventDefault();
var file_data = $('#upload-pic').prop('files')[0];
var formData = new FormData(this);
$.ajax({
method: "POST",
url : "AJAXSubmitClientData.php",
data :formData,
dataType : "html",
contentType: false,
enctype: 'multipart/form-data',
cache: false,
processData:false,
success:function(data)
{
alert(data);
}
});
Php code Here the description is inserting but file not
if(isset($_POST['formData']))
{
$file = array(
"name" => $_FILES['form_data']['name'],
"tmp_name" => $_FILES['form_data']['tmp_name']
);
print_r($file);
$fileinserted = $objMaster->imageinsert($file);
$dataDescription = array(
"description" => $_POST['description'],
"projectProfile" => $fileinserted,
);
echo $insertdata = $objMaster->updateJobPostTable($dataDescription,$_SESSION['lastinsertid']);
echo 1;
}
imageinsert Function
public function imageinsert($file, $path = "") {
$fname = "";
$uploadpath = "";
if ($path == "") {
$uploadpath = $this->upload1;
} else {
$uploadpath = $this->upload1 . $path . "/";
}
$current_timestamp = $this->timeStamp();
$filename = basename($file['name']);
$newname = $current_timestamp . $filename;
if ((move_uploaded_file($file['tmp_name'], $uploadpath . $newname))) {
$fname = $newname;
}
return $fname;
}
Any help is appreciated
HTML Page :-
change the button property value to type="button" instead of type="submit" & add onclick Event Attribute.
<form id="descriptionsubmit" action="" method="post" enctype = "multipart/form-data">
<textarea class="form-control" name="textarea-description" placeholder="Write Something"></textarea>
<input type="file" name="upload-pic" id="upload-pic" class="inputfile" >
<button type="button" onclick="addData()" class="update-btn">Next</button>
</form>
JS AJax Code:-
function addData() {
var formData = new FormData($('#descriptionsubmit')[0]);
formData.append('action', 'add');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'AJAXSubmitClientData.php',
data: formData,
success:function(msg){
alert(msg);
}
});
}
AJAXSubmitClientData.php
<?php
include('dbconn.php');
if(isset($_POST["action"]) && $_POST["action"]=="add"){
echo $a = $_POST["textarea-description"];
echo $g = $_FILES["upload-pic"]["name"];
// insert code here.
}
?>
After I've uploaded an image my page refreshes and I'm not sure how to stop that from happening. I do have e.preventDefault().
I do know that it might have to do with this line
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
Here is my code
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
$(".upload-area").on('drop', function(e){
e.preventDefault();
var files_list = e.originalEvent.dataTransfer.files;
var formData = new FormData();
for(i = 0; i < files_list.length; i++){
formData.append('file[]', files_list[i]);
}
uploadData(formData);
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadData(formdata){
$.ajax({
url: 'upload.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
addThumbnail(response);
}
});
}
function addThumbnail(data){
var len = $("#uploadfile div.thumbnail").length;
var num = Number(len);
num = num + 1;
var src = data.src;
// console.log(len);
$("#thumbnail_"+num).append('<img src="'+src+'" width="100%" height="78%">');
}
my upload.php
$allowed = ['png', 'jpg'];
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $filename,"size" => $filesize);
}
echo json_encode($return_arr);
}
my index.php
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>
Put submit button in hidden format. Follow below steps.
In HTML,
<input type="submit" id="submitBtn" style="display:none;">
In Javascript,
function submitMe() {
$("#submitBtn").trigger("click");
}
$(".upload-area").on('drop', function(e){
----
----
submitMe();
});
I have an error when I try to upload an image using jQuery and ajax.
Here is my html:
<label for="img_add_galery">
<a class="add">
<img click="image_galery" src="../../img/ui/black.png" alt="images">
</a>
</label>
</div>
<input type="file" id="img_add_galery" name="img_add_galery" style="display:none;"/>
This is my js:
$(document).on('change','#img_add_galery',function(){
var property = document.getElementById('img_add_galery').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('invalid image type');
}
var image_size = property.size;
if(image_size > 2000000000000)
{
alert('image is to big');
}
else
{
console.log(property);
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: "traitement/add_image_galery.php",
method: "POST",
data: form_data,
contentType:false,
cache:false,
processData:false,
success:function(data)
{
$(".tz-gallery").children().append(data);
}
})
}
})
and my php
var_dump($_FILES["img_add_galery"]["name"]);
if($_FILES["file_img"]["name"] != '')
{
$test = explode(".",$_FILES["file_img"]["name"]);
$extension = end($test);
$name = rand(1,9999) . '.' . $extension;
$location = '../../../img/galerie/'.$name;
move_uploaded_file($_FILES["file_img"]["tmp_name"],$location);
echo '<div class="col-sm-6 col-md-4">
<a class="delete" img="'.$location.'">
<img click="image_galery" src="'.$location.'" alt="images">
</a>
</div>';
}
When you append the file to your FormData object you use file as its name but in PHP you use file_img, both must match.
$_FILES["file"]["name"]
In fact, I think you should use the same name everywhere just to avoid confusion
<input type="file" id="img_add_galery" name="img_add_galery" style="display:none;"/>
form_data.append("img_add_galery", property);
$_FILES["img_add_galery"]["name"]
Also if you want to check what's going on in the file array you should dump the whole thing var_dump($_FILES);
I'm trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I'm redirecting to an iframe ("myFrame") to stop the page reloading but it appears this doesn't work correctly. What did I do wrong?
HTML
<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
<input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
<label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>
<iframe class="hidden" name="myFrame"></iframe>
SCRIPT
function uploadPix(){
var form = document.getElementById('upload');
form.onsubmit = function(e){
e.preventDefault()
var formData = new FormData(this);
$.ajax({
url: 'sql/main-pix-upload.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
})
});
};
PHP
$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];
$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
mkdir($pathPix, 0777, true);
}
$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);
if(0 < $_FILES['main_pix']['error']){
echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
move_uploaded_file($temp, $target_file);
}
Either use:
form.onsubmit = function(e) {
e.preventDefault()
};
or:
form.addEventListener("submit", function(e) {
e.preventDefault();
});
And then you have to make the HTTP-Call by yourself using AJAX.
I'm sure I've made a simple error on this one. The file isn't being passed to the php page (I get the "Not uploaded:File error. Please try again." error passed back from the PHP page.)
The code works fine without the JQUERY so I guess the PHP is not the problem.
I've checked the field name / id & it seems OK. I tried testing to see if the value of the button was being passed and it wasn't, that's when I came to the conclusion it was probably the JQUERY but then I was stumped.
I know similar posts have been submitted (I've read them) but I'm desperate!!
Thank you in advance.
Here's the HTML:
<form action="upload.php" name="formname" ENCTYPE="multipart/form-data" id="formid">
<fieldset>
<legend>File info</legend>
<p>
<label for="file1">Files<span class="red"> *</span></label>
<input name="file1" type="file" />
</p>
</fieldset>
<p><label> </label><input type="button" id="submit" value="Add" /></p>
</form>
<div id="output"></div>
<script>
$(function(){
$('#submit').on('click', function(){
var fd = new FormData($("#formid"));
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
and the PHP
<?php
$strName = 'JoeBloggs';
$intId = 1045;
$missing = '';
date_default_timezone_set("Europe/London");
error_reporting(E_ALL);
include('class.upload.php');
// where to put the images?
$dir_dest = '../'.$intId.'/';
$xcount = 0;
if (!file_exists($dir_dest)) { mkdir($dir_dest, 0777, true);}
# upload 1400px
$handle = new upload($_FILES['file1']);
if ($handle->uploaded) {
$y = $handle->image_src_y;
$height = $y/2;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 260;
$handle->image_convert = jpg;
$handle->Process($dir_dest);
if ($handle->processed) {
// everything was fine !
$strFilename1 = $handle->file_dst_name;
rename( $dir_dest . $strFilename1, $dir_dest . $strName . '.jpg' );
$missing .= 'File uploaded';
} else {
$missing .= $missing. 'Not processed:' . $handle->error . '<br />';
}
} else {
$missing .= 'Not uploaded:' . $handle->error . '<br />';
}
echo $missing;
//header('Location: ../index.php?missing='.$missing);
?>
<img src="<?= $dir_dest . $strName?>.jpg" />
Try this will may help you,
<script>
$(function(){
$('#submit').on('click', function(){
var form = $('#formid')[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
try adding to the ajax function:
contentType: multipart/form-data