Onclick button i am and trying to save 2 different images.
I am passing One image through ajax & another through form, but i can able to download only one image at a time. Will it create any conflicts ?
Do i need to have correct Content-Length header for both image ?
Html
<div id="target">
<div id="container" class="container"></div>
</div>
<input type="submit" value="Save" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
Script
function capture()
{
// one image
var canvas = document.getElementById("1");
var dataURL = canvas.toDataURL(); // THE BASE 64 DATA
var dataFileName = document.getElementById('fileup').value.replace(/.*(\/|\\)/, ''); // GET THE FILE NAME THAT USER CHOSE
var dataFileType = dataFileName.split('.').pop();
data = new FormData();
data.append('imgBase64', file, file.name);
$.ajax({
type: "POST",
url: "save.php",
cache:false,
contentType: false,
processData: false,
data: data
}).done(function(o) {
var response = JSON.parse(o);
$('body').prepend('<img src="/var/www/html/ecom1/site/test/final/' + response.data[0].fileName + '" style="height: 200px; width: auto;">');
});
//another image
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
document.getElementById("myForm").submit();
}
});
}
php
<?php
// One image code :
if (isset($_FILES['imgBase64']))
{
$fname = $_FILES["imgBase64"]["name"]; // THE FILENAME THE USER CHOSE IS RECEIVED VIA POST
$img = filter_input(INPUT_POST, 'imgBase64'); // THE BASE64 ENCODING RECEIVED VIA POST
$imgtype = $_FILES["imgBase64"]["type"]; // THE FILE TYPE / EXTENSION IS RECEIVED VIA POST
if(move_uploaded_file($_FILES["imgBase64"]["tmp_name"], "/var/www/html/ecom1/site/test/final/".$fname))
{
echo '{"error":false, "message":null,"data":[{"msg": "Image has been saved successfully!", "fileName": "' . $fname . '"}]}';
}
else
{
echo '{"error":true, "message":"File not uploaded"}';
}
}
// another image code :
//Show the image
echo '<img src="'.$_POST['img_val'].'" />';
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
file_put_contents('/var/www/html/ecom1/site/test/final/img.png', $unencodedData);
?>
Here is Full html & php code
Related
I want to upload a product with multiple images using Dropzone, I have a form which has other fields like price, name etc. I have seen other tutorials but they only upload images not images with other fields(price, name) at once. I have set the Dropzone which shows the preview but if I submit the button I get a validation Please enter product image. How can I pass images to the controller using Dropzone?
Controller
public function store(Request $request)
{
$formInput=$request->except('filename');
$product = product::create(array_merge($formInput, [
'user_id' => Auth::user()->id
]));
foreach ($request->file as $photo) {
$filename = $photo->store('public/photos');
ProductsPhoto::create([
'product_id' => $product->id,
'filename' => $filename
]);
}
}
Blade
//The form
<div class="panel-body">
<form>
#csrf
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="pro_name">Name</label>
<input type="text" class="form-control" name="pro_name" id="pro_name" placeholder="Enter product name">
<label for="pro_price">Price</label>
<input type="text" class="form-control" name="pro_price" id="pro_price" placeholder="Enter price">
<label for="photos">Choose 5 Images</label>
<div class="needsclick dropzone" id="document-dropzone"> // Display images preview
</div>
<input type="submit" class="btn btn-primary" value="Submit" id="btn"/>
</div>
Ajax
//This is how I submit the form
<script>
var token = $("#token").val();
$(document).ready(function(){
$("#btn").click(function (e) {
e.preventDefault();
$("#loading").show();
var url = '{{ route('product.store') }}';
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
formData.append('_token', token); // adding token
$.ajax({
url: url,
data: formData, //just that without variables
type: 'POST',
cache: false,
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("Product has been added successfull");
$("#msg").fadeOut(3000);
window.location.href = "<?php echo url('seller/product') ?>";
$("#loading").hide();
}
else{
printErrorMsg(data.error);
}
}
});
function printErrorMsg (msg) {
$("#loading").hide();
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
});
var uploadedDocumentMap = {}
Dropzone.options.documentDropzone = {
url: '{{ route('product.store') }}',
maxFilesize: 10, // MB
addRemoveLinks: true,
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
success: function (file, response) {
$('form').append('<input type="hidden" name="document[]" value="' + file.name + '">')
uploadedDocumentMap[file.name] = response.name
},
removedfile: function (file) {
file.previewElement.remove()
var name = ''
if (typeof file.file_name !== 'undefined') {
name = file.file_name
} else {
name = uploadedDocumentMap[file.name]
}
$('form').find('input[name="document[]"][value="' + name + '"]').remove()
},
init: function () {
#if(isset($project) && $project->document)
var files =
{!! json_encode($project->document) !!}
for (var i in files) {
var file = files[i]
this.options.addedfile.call(this, file)
file.previewElement.classList.add('dz-complete')
$('form').append('<input type="hidden" name="document[]" value="' + file.file_name + '">')
}
#endif
}
}
</script>
Some things are not right in your code AND your concept (at least in my opinion):
You need to prevent the default behavior of the #btn because you need to intercept the form submission. Otherwise, the form will just get submitted as a GET request (what is the default behavior).
$("#btn").click(function (e) {
e.preventDefault();
// ...
}
The <form> element is not closed. Furthermore, don't override the _ token in your JavaScript but just add #csrf to the form. Larvel and jQuery will handle everything for you.
<form>
#csrf
I think I understood what you were trying to achieve now. Dropzone is uploading (= POST request) the files directly, so you need a separate route (or another code branch) to handle the file upload. Then, you can get the filename of the previously uploaded file and attach it as a hidden input field like so:
success: function (file, response) {
$('form').append('<input type="hidden" name="document[]" value="' + file.name + '">')
},
What you will receive in your controller's method is the pro_name, pro_price and an array document containing the names of the uploaded files. Following your logic, the file must be already existing in the storage because it was uploaded by the Dropzone action. You could then save the filename to the database or whatever and use it as a reference for accessing the file later.
Anyway, I would not recommend to use the client-provided filename for storage because it may not be unique. Laravel offers a lot of helpful tools for this scenario: https://laravel.com/docs/5.7/filesystem#file-uploads
so i have a form update but my problem is i cant save my image into my database only the file path..
here is my code.
<form action="" id="update_profile" method="POST" enctype="multipart/form-data">
<div class="col-md-4">
<img class="img-responsive" id="profile_image" name="profile_image" src=""/>
<input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)">
</div>
<input type="text" id="users_lastname" name="users_lastname" class="form-control" value="">
</form>
from the form update i use ajax to display the data from my database to the form fields..
$.ajax({
url:'../ajax/getprofile.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#profile_image').attr('src',result.profile_image);
$('#users_lastname').val(result.users_firstname);
},
error:function(status){
}
});
$('#update_profile').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../ajax/update_profile.php',
type:'POST',
data: formData,
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
success:function(result){
console.log(result);
},
error:function(status){
// console.log(status.responseText);
}
});
});
and use another ajax for submitting the form so basically what happens is from the <img src="../assets/img/faces/avatar.jpg"> this is where i display my image from my db. and when i click the <input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)"> <img src="../assets/img/faces/koala.jpg"> will change its value...
if (isset($_POST)) {
$users_lastname = $_POST['users_lastname'];
$profile_image = $_POST['profile_image'];
$imgFile = $_FILES['image']['name'];
$tmp_dir = $_FILES['image']['tmp_name'];
$imgSize = $_FILES['image']['size'];
}
if($imgFile)
{
$upload_dir = '../assets/img/faces/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 2000000)
{
// unlink($upload_dir.$_SESSION['image']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
echo '<script>
alert("Sorry, your file is too large it should be less then 2MB");
</script>';
}
}
else
{
echo '<script>
alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
</script>';
}
}
else
{
$userpic = $imgs; // old image from database
$userpic = substr($userpic,20);
}
if(!isset($errMSG))
{
$path = '../assets/img/faces/'. $userpic;
$action= 'Updated his/her information';
$logs= $log->insertLogs($usernm,$action);
$res = $users->Userupdated($user,$users_firstname,$users_lastname,$users_email);
$data = $users->updateUserdetail($user,$path,$profile_contact,$profile_address,$profile_department,$profile_specialization,$profile_aboutme);
}
else{
$errMSG = "Sorry Data Could Not Updated !";
}
but when i tried to upload without replacing the image from the src. what happens is it only uploads the location path not the exact image. also when i replace the image it only uploads the location path.. i dont know if this is the correct approach for getting the src image any idea for this?
Try this, I used this in one of my proect:
var form = $("#update_profile").get(0);
e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form
$.ajax({
url: '../ajax/update_profile.php',
type: 'POST',
data: new FormData(form),
dataType: 'json',
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (response) {
},
error: function (data) {
}
});
I have this HTML form that works currently. It lets you choose an image and it uploads to my server (changing it to have a max height or width of 200) and then displays the image back on the form to show the user...
<div id="preview"><img id="image" src="no-image.jpg" /></div>
<form id="form" action="" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
Here is the Jquery...
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload-image-ajax.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#image").attr('src', data);
/* $("#preview").html(data).fadeIn();*/
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
And here is the PHP the Jquery calls...
<?php
require_once("includes/session.php");
$poolid=strtolower($_SESSION['poolid']); //lowercase it first so we get exact matches
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// check's valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid. ".png";
$path = $path.strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst, $path); // adjust format as needed
imagedestroy($dst);
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
?>
Again this all works fine when this form is by itself on a page. However, I now want this Image Upload area to be part of a much larger form. I tried adding the exact HTML inside another larger form and as you might have guessed, when I click "upload" to upload the image, it tries to submit the larger form.
I would like it to simply upload/resize the image without submitting the larger form, display the image back to the user and let them continue filling out other form inputs.
I tried removing the form elements (so there was no more nesting of form tags), so the HTML was reduced to this (notice I changed the input type of "submit" to now be "button")...
<div id="preview"><img id="image" src="no-image.jpg" /></div>
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
<div id="err"></div>
Then in the Jquery, I removed the .on submit stuff and replaced it with .click, since I just want this image stuff to happen on click, not on any type of submit.
$(document).ready(function () {
$("#button").click(function(){
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
//Make ajax call here:
$.ajax({
url: 'upload-image-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: imageData,
beforeSend : function() {
$("#err").fadeOut();
alert('hi');
},
success: function(result) {
alert('succ');
if(result=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#image").attr('src', result);
/* $("#preview").html(data).fadeIn();*/
$("#form")[0].reset();
}
},
error: function(result) {
alert(result.responseText);
$("#err").html(result).fadeIn();
}
});
});
});
Again, I am reading about the data and dataType settings at http://api.jquery.com/jquery.ajax/, but I cannot grasp it for the life of me (no experience with JSON probably isn't helping me).
Can someone please speak towards the var imageData and .append part of my new Jquery, as I assume that must be where things are going off the rails. As is often the case, this seems like it should be super easy to accomplish since I have it working fine on its own, but it's driving me insane.
I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.
Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);
//Communicate with the server
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // 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
{
$('#loading').hide();
$("#message").html(data);
}
});
Here is my PHP script to handle the sent file and save it in a specified folder.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>
When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.
Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?
Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:
$('#upload').on('click', function(e) {
$('#message').fadeOut();
e.preventDefault();
if ($('#file')[0].files.length == 0) {
alert('Choose a file!');
} else {
var file_data = $('#file').prop('files')[0]; //file object details
var form_data = new FormData($('#form')[0]);
form_data.append('file', file_data);
var unique_identifier = $('#unique_identifier').val();
$.ajax({
url: 'upload.php',
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response) {
$('#message').html(php_script_response).fadeIn();
//alert(php_script_response); // display response from the PHP script, if any
}
});
}
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
<input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
<input type='file' name='file' id='file' />
<a id='upload'>Upload</a>
</form>
And the PHP script I made:
$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination)
Also, I recomend you to do some PHP validation.
It seems you are not appending the file to uploaded to the form data, May be you need something like this.
var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
url: "ExecuteMaya.php",
type: "POST",
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function(result){
// your code executed successfully
}
I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.