Save image from blob-url (javascript / php) - javascript

With pdf-js I filter images of an PDF-File. After this I display all of the images in a div. The elements look like this:
<img src="blob:http://myhost/07eee62c-8632-4d7f-a086-c06f1c920808">
What I want to do, is to save all of this images in a server's directory. But I don't know how to do this.
i tried this, but I think it's totally wrong:
let form_data = new FormData();
fetch(url)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here's where you get access to the blob
// And you can use it for whatever you want
// Like calling ref().put(blob)
// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.src = objectURL;
console.log(id, url, selectedProject, pdfName);
form_data.append('file', myImage);
form_data.append('path', dest);
form_data.append('project', selectedProject);
form_data.append('url', url);
});
$.ajax({
url: 'upload_referenceFile.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
}
});
php:
$project = $_REQUEST['project'];
$script = $_REQUEST['path'];
$dest = 'data/' . $project . '/' . $script . '/media/';
_log($_REQUEST['file']);
$exists = file_exists($dest . $_FILES['file']['name']);
if($exists){
}else{
if (!file_exists($dest)) {
if (!mkdir($dest, 0777, true) && !is_dir($dest)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dest));
}
}
move_uploaded_file($_FILES['file']['tmp_name'], $dest . $_FILES['file']['name']);
}

Related

How to upload an image to server directory using ajax?

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.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') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

Save the circular crop image from Cropper

I'm using Cropper to crop the images in a circular shape from this example:
https://github.com/fengyuanchen/cropperjs/blob/master/examples/crop-a-round-image.html
Here is a fiddle: http://jsfiddle.net/7hsr98w4/7/
That's how the cropped image looks like:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEUAAABFCAYAAAAcjSspAAAMJklEQVR4XtWca5AU1RXHzwAu8hBFcYmAEYLrqkgWxZj4oBBRgSjBB66m8iGaqjyofEjyJWo+JJpUXlWpMn5KqFiRfEmyhfERYgRfgSIESwm4GlCxRBREEBFFVB6yk9+/p3u2u7d7+vY8dmdP1d2Znel777n/Pufcc849PQXrRyoWi+cx3Tm0SbTTY6/6bCdtR8Lry4VC4X/9xWqhkRMBwlDGn0X7Cm0R7XM1zLeNvo/4bS0g9dQwVsWuDQEFMK5h1ptpej25Acy/w5j/oD0IOI/We/y6ggIYkoif06Qm/UUvMtGPAEcg1YXqAgpgfAlu7qHpdaBoHRPfDjh6rYlqAgUwzm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P3TYVGsggi2SH1OJFxGXA8H/0/bCQHxSoi7b3x6L1z46gyGSdD384T8mUWbnERPjyXrVqXZ7iKCjVqLNokdRIZaUqN/ePL3rZVKnHxexmXHtBCBTla3W9qiYJHRyBCIaVczYLQF6oJKiZoPgSo4KeP9Pq+rxPQQdqEydaUaeIaXetjccDZrK7KNtzCAeQo9gixX1VkFy5+QCSPpk/qBMoPjB6Al3AVH+2EVtJoGKV7nahgLSMJk5TFeRuahVXrswrHZpVBXidzOf07LIzKD4wUqUHaZOruFMD1YV6EFsEIEmnsYk85QLFB0YG4e8031oO1Fqd5lUZrB6Ry3WkmBsUHxjVyd1LS3xexondxl90H1N8F0AcCnqjzFQFSjAEtuAK3v+syaRG0qEn2FdXi3tNoITA+bIPjmqeB4pwXOzHgFHzr2TUBRRfpTTW9bSf0vyHAfsFHyJA74RTPxtSl6cv6wZKePmolX43hajQ+2EI56dCckA4eH4/Jb4owJGzp0BHPk6tv7SjVKl+aUc733qkYnD90k7aHQckhccqz47/HlPwv+KSpN9l6gYEZSv7hf4Pc6aU1pSTzEUAAAAASUVORK5CYII=">
Then I use Ajax to send that blob to PHP to upload that image:
document.getElementById('button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob);
// Use `jQuery.ajax` method
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
console.log('Upload error');
}
});
});
});
This code could be found here:
https://github.com/fengyuanchen/cropperjs#getcroppedcanvasoptions
In upload.php:
print_r($_FILES);
if(isset($_FILES['avatar']) and !$_FILES['avatar']['error']){
file_put_contents("uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']));
}
exit();
That's the response from print_r($_FILES):
Array
(
[avatar] => Array
(
[name] => blob
[type] => image/png
[tmp_name] => C:\xampp\tmp\php2BDA.tmp
[error] => 0
[size] => 2135
)
)
When I console.log() blob, I get and Object:
Blob(2135) {size: 2135, type: "image/png"}
But when I view the image on the uploads folder, It's a rectangular image not circular.
Here is how it's previewed after cropping:
And that's how it's previewed on uploads folder:
Both images(previewed and saved) are 360x360.
How to save the cropped image in circular shape like how it's previewed after cropping?
You need to add rounding box css for .cropper-crop-box also
.cropper-crop-box, .cropper-view-box {
border-radius: 50%;
}
If you want circular view box you can use this
.cropper-view-box {
box-shadow: 0 0 0 1px #39f;
outline: 0;
}
UPDATE:
Sorry I misunderstood your question actually what you wanted was pretty straightforward
You already have getRoundedCanvas() which gets you the rounded version of crop, so just need to use it in your ajax call like
document.getElementById('button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
//only this line is changed
getRoundedCanvas(cropper.getCroppedCanvas()).toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob);
// Use `jQuery.ajax` method
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
console.log('Upload error');
}
});
});
});
I think that this function getroundedcanvas() doesn't exist with the jquery-cropper.js, if it was you, you have already done a great job with your function, I really needed it badly this is what I added and uploaded it with PHP.
case 'getCroppedCanvas':
if (result) {
// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`.
// The default value for the second parameter of `toBlob` is 'image/png', change it if necessary.
// Round
var roundedCanvas = getRoundedCanvas(result);
// Show
$('img.MyImage').attr('src',roundedCanvas.toDataURL());
var roundedBlob ;
roundedCanvas.toBlob((blob) => {
roundedBlob = blob;
});
result.toBlob((blob) => {
const formData = new FormData();
// Pass the image file name as the third parameter if necessary.
formData.append('UploadPhoto', blob, 'profil.png' );
formData.append('CircleBlob', roundedBlob, 'circle.png' );
$.ajax(document.location.pathname, {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success(response) {
console.log(response);
console.log('Upload success');
$('#imgResizeModal').modal("hide");
},
error() {
console.log('Upload error');
},
});
}/*, 'image/png' */);
}
break;

ajax passing two forms with codeigniter

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}
Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

How to upload file using ajax/jQuery with Symfony2

Could anyone help me?
I'm trying to write a script that when the user clicks an image, that this triggers an image in the database to be updated.
For this I wrote the code which temporarily makes the Caller Line of the method in the controller, but when I send the form it is not validated because of Cross-Site-Request-Forgery.
$("#upload_picture").on('click', function (e) {
e.preventDefault();
$("#bundle_user_file").trigger('click');
});
$("#bundle_user_file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.active-img').attr('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
ajax_formData()
}
});
This is my Caller Line ajax, is do the treatment in the form with the FormData to post, caught the routes and the token. He calls route, but not sure if the image is going or not, even with the Inspector firefox.
function ajax_formData() {
var at = $("form[name=bundle_user]");
var formData = new FormData();
formData.append('file', $("input[type=file]")[0].files[0]);
var url = at.attr('action') + '?_token=' + $("#bundle_user__token").val();
$.ajax({
type: "PUT",
url: url,
data: formData,
success: function (data) {
alert("success: " + data.message);
},
fail: function (data) {
alert("error: " + data.message);
},
cache: false,
contentType: false,
processData: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
myXhr.upload.addEventListener('progress', function () {
/* faz alguma coisa durante o progresso do upload */
}, false);
}
return myXhr;
}
});
}
This is the method in controlodor it with a common call with the click the button to submit change my image. But as I said before the ajax call, he replied that the Token not available
public function updateAction(Request $request, $id)
{
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$entity = $this->getUser();
if ($entity->getId() != $id) {
$response = new JsonResponse(
array(
'message' => 'Não tem permissao'
), 400);
return $response;
}
$form_update = $this->updateForm($entity);
$form_update->handleRequest($request);
if ($form_update->isValid()) {
$entity->upload();
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
$response = new JsonResponse(
array(
'message' => $form_update->getErrors()
), 400);
return $response;
}
Firstly, I notice that your click event for #upload_image fires a click trigger on #bundle_user_file, but below that you are asking it to look for a change event. Therefore, this would do nothing.
You can re-generate a CSRF token if you want by calling the csrf token_manager service by doing this:
/** #var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken($tokenId);
return new Response($token);
You can determine $tokenId in your form, if you want, or just use your picture ID, or whatever. Normally the CSRF token is generated automatically from your session, so you might want to check that too.
function upload_img(){
var file_data = $('.myform').find('.drawing').prop("files")[0];
var form_data = new FormData();
form_data.append("drawing", file_data);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
contentType: false,
dataType:'json',
cache: false,
processData:false,
success: function(data)
{
},
error: function()
{
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='myform'>
<input type='file' class='drawing' onchange='upload_img()' >
</form>

File upload via Ajax in Laravel

I'm trying to upload a file through ajax in Laravel.
$("#stepbutton2").click(function(){
var uploadFile = document.getElementById("largeImage");
if( ""==uploadFile.value){
}
else{
var fd = new FormData();
fd.append( "fileInput", $("#largeImage")[0].files[0]);
$.ajax({
url: '/nominations/upload/image',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
if(data.uploaded==true){
alert(data.url);
}
},
error: function(err){
alert(err);
}
});
}
});
I'm passing the file input to the php script.
public function image(){
$file = Input::file('fileInput');
$ext = $file->getClientOriginalExtension();
$fileName = md5(time()).".$ext";
$destinationPath = "uploads/".date('Y').'/'.date('m').'/';
$file->move($destinationPath, $fileName);
$path = $file->getRealPath();
return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);
}
I'm getting a the response as
{"success":true,"uploaded":true,"url":false}
The request Payload is
------WebKitFormBoundary30GMDJXOsygjL0ZS
Content-Disposition: form-data; name="fileInput"; filename="DSC06065 copy.jpg"
Content-Type: image/jpeg
Why this is happening?
Found the answer:
public function image(){
$file = Input::file('fileInput');
$ext = $file->getClientOriginalExtension();
$fileName = md5(time()).".$ext";
$destinationPath = "uploads/".date('Y').'/'.date('m').'/';
$moved_file = $file->move($destinationPath, $fileName);
$path = $moved_file->getRealPath();
return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);
}
Get the path after assigning it to a new variable.

Categories

Resources