I'm trying to upload images using the FileReader API, and writing the data URL from the FileReader.readAsDataURL() method to a file using PHP on the server side.
The method works with smaller images (not sure exactly how small, but < 1MB is probably fairly acurate). However, when uploading larger images, I get a 413 Request Entity Too Large error. I saw this question and tried both of the solutions, however the first did nothing and the second gave a 500 error. When I checked the error log it said:
/home/username/public_html/.htaccess: LimitRequestFieldsize not allowed here
Why isn't this working?
php.ini
file_uploads = On
post_max_size = 50M
upload_max_filesize = 50M
.htaccess
RewriteEngine On
# LimitRequestFieldSize 2097152
SSLRenegBufferSize 1000000
JS
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$.ajax({
url: "?action=saveImg",
type: "POST",
dataType: "json",
data: {
image: e.target.result,
id: id
},
success: function(data){
$.dialog(data.message, data.title);
}
});
}
for(var i = 0; i < input.files.length; i++){
reader.readAsDataURL(input.files[i]);
}
}
}
$("#file").change(function() {
readURL(this);
});
PHP
$id = $_POST["id"];
$filetype = str_replace('data:', '', explode(";", $_POST["image"])[0]);
$data = $_POST["image"];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$rand = random_str(6);
$ext = explode("/", $filetype)[1];
if(!is_dir("../../images/product/{$id}/")){
mkdir("../../images/product/{$id}/");
}
$fh = fopen("../../images/product/{$id}/{$rand}.{$ext}", "w+");
fwrite($fh, $data);
fclose($fh);
$return = ["message" => "ID is $id. Saved image as /images/product/{$id}/{$rand}.{$ext}.", "title" => "Saved Image", "image" => "/images/product/{$id}/{$rand}.{$ext}"];
echo json_encode($return);
die();
How can I make this work?
This is an apache config issue
There are many potential causes of this issue, aside from LimitRequestFieldsize.
LimitRequestFieldsize
First, LimitRequestFieldsize usually must be set in a .conf file, rather than .htaccess. Additionally, there are significant security implications to increasing the limit. (slow loris attack for one)
SecRequestBodyLimit (if you're using mod_security)
Also must be set in a .conf file. Also has security implications.
SecRequestBodyLimit 10485760
Your question belongs on ServerFault
Related
I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.
I have integrated summernote in my website (built with Codeigniter) and for texts it is working fine. But for image upload, there arises the following problem.
Summernote reads the image as base64. Now this works perfectly fine for small images, but once images are large, the image finally does not render due to the huge string created by the base64 in the database.
So I am trying to save the image in my server and then use the link of that image.
Following are the codes:
Script for summernote:
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
onImageUpload: function(files) {
sendFile(files[0]);
}
});
function sendFile(file) {
data = new FormData();
data.append("files", file);
upload_url = "<?php echo base_url(); ?>" + "general/upload_image";
$.ajax({
data: data,
type: "POST",
url: upload_url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(this).summernote("insertImage", url);
}
});
}
});
the php upload_image function:
public function upload_image()
{
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'http://sitename.com/dist/img/blogimg/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://sitename.com/dist/img/blogimg/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
now, when I click on insert image in summernote or drag and drop an image multiple instances of the following error is shown in the console:
>Uncaught TypeError: Cannot read property 'nodeType' of undefined
This is what I want to achieve,
N.B. This editor is for a blog.
1. User clicks on insert image and uploads an image from his computer.
2. the image is shown in the editor (but not uploaded to server at this step).
3. When user clicks on submit button, then the image should be saved as an image file in a predefined folder.
4. When the page renders the it should have
<img src="mysite.com/path_to_image">
now it is something like
<img src="data:image/jpeg;base64,/9j/4AAQSkZJR....">)
Please note, I tried using onImageUpload within callbacks but the result was nothing was actually happening, neither the image was geting uploaded to the editor nor to the folder in the server.
Where am I going wrong....?? Please help me fix this...
if your summernote version after 0.7
following this
$('#summernote').summernote({
height: 400,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0]);
}
}});
Okay, although I could not find a solution to my problem, I have implemented an alternation solution and it works perfectly, although pt. 3 is not catered to and the image is uploaded to the server in an earlier step. That too can be catered with some js scripts...Will do that later... What I did is I targeted the summernote ids and classes and added my codes in place of theirs...
I removed their upload image field by this code:
<style>
/*to disable the upload image from computer uncomment this css code.*/
.note-group-select-from-files {
display: none;
}
</style>
Next I inserted my HTML below their insert link field this way:
document.getElementsByClassName('note-group-image-url')[0].insertAdjacentHTML('afterend','<p class="sober"><p>Click here to upoad image</p></i></p>');
Next I handled the image upload through a modal and wrote a custom js script that copied the image url to the field of .note-image-url
Also I had to customise the javascript of the insert image button of summernote with js so that users can directly click on insert image.
You can add this to your store/ update controller.
It will detect images in your editor, convert and save it in your server.
$body = $data['content'];
$doc = new DomDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($body);
$images = $doc->getelementsbytagname('img');
define('UPLOAD_DIR', 'assets/images/announcement_img/');
foreach($images as $k => $img){
$datas = $img->getattribute('src');
if (strpos($datas, 'data:image')!==false){
list($type, $datas) = explode(';', $datas);
list($media, $format) = explode('/', $type);
list(, $datas) = explode(',', $datas);
$datas = str_replace(' ', '+', $datas);
$datas = base64_decode($datas);
$file= UPLOAD_DIR . time().$k.'.'.$format;
$success = file_put_contents($file, $datas);
print $success ? $file : '<br><br>Unable to save the file.<br><br>';
$img->removeattribute('src');
$img->setattribute('src',base_url().$file);
}
}
$body = $doc->savehtml();
$data['content']=$body;
I am fairly new to C++ and also Dlib. I need to work on a facial landmark detector for browser and was wondering if someone has tried compiling DLIB with e.g. ASM.js to work on a browser. I have not seen many DLib facial landmarking live demos on the web.
Is it a worthwhile idea to pursue? If yes, could someone direct me to any resources?
I am also face same problem in one of the my project. But i successfully get face landmark details from dlib with browser.
Actually i get image from user and send to server save it one specific folder. then trigger dlib python code through PHP and get landmark point details as a json format. once we get a point details we can do anything with that.
idea is
input image file --> send to serve --> save to folder --> trigger dlib python script --> save point as a json file --> echo to success --> get json
through this way:
STEP 1:
first install Dlip on your server successfully(first tested your local server) without any error. and check it its run without error.
STEP 2:
Then we want face landmark from dlip. dlip have a example script face_landmark_detection.py we can use this.
my customized face_landmark_detection.py script this is save point details as a json file in specific path:
# python face_landmark_detection.py "predictor.dat" "folder/image.jpg" "folder/test.json"
import dlib
import glob
import json
import os
from skimage import io
import sys
predictor_path = sys.argv[1]
#faces_folder_path = sys.argv[2]
image = sys.argv[2]
json_path = sys.argv[3]
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
img = io.imread(image)
dets = detector(img, 1)
print(dets);
print("Number of faces detected: {}".format(len(dets)))
for k, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
k, d.left(), d.top(), d.right(), d.bottom()))
# Get the landmarks/parts for the face in box d.
shape = predictor(img, d)
print("Part 0: {}, Part 1: {}, Part 3: {} ...".format(shape.part(0),
shape.part(1), shape.part(2), ))
part1 = shape
data = {}
num = 0
for n, p in enumerate(shape.parts()):
n = format(n)
p = format(p)
p = p.split(",")
x = p[0].split("(")
x = x[1]
y = p[1].split(" ")
y = y[1].split(")")
y = y[0]
print(n, x, y)
data[n] = {'x':x, 'y':y}
out_file = open(json_path, "a")
json.dump(data, out_file, sort_keys=True, indent=4)
json_data = json.dumps(data, sort_keys=True);
print(json_data)
my server php script . this script get image from browser and save it in some folder and trigger my face_landmark_detection.py with predictor path ,image path, json path arguments.
server.php file like this
<?php
$target_dir = "/designing/face/uploads/";
$type = explode("/", $_FILES["file"]["type"]);
$type = $type[1];
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST)) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
unlink($target_file);
$uploadOk = 1;
}
// Check file size
/* if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
} */
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "error";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
//chmod($target_file, 0777);
//echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
if ($imageFileType == "png") {
$image = imagecreatefrompng($target_file);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 100; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $target_file . ".jpg", $quality);
imagedestroy($bg);
unlink($target_file);
$target_file = $target_file . ".jpg";
//echo $target_file;
}
$json_file = fopen("/test/json/" . $_FILES["file"]["name"] . "_json.txt", "w");
if ($json_file) {
$command = 'python /face/face_landmark_detection.py "/face/predictor.dat" "' . $target_file . '" "/test/json/' . $_FILES["file"]["name"] . '_json.txt"';
$output = shell_exec($command);
if ($output) {
//unlink($target_file);
echo "ok";
}
}
//echo $command;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
and my client (browser) side script like this
$('#file').change(function() {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
img = $('input[type=file]')[0].files[0];
file_name = img.name;
console.log(file_name);
var reader = new FileReader();
reader.onload = function(readerEvt) {
data_url = readerEvt.target.result;
};
reader.readAsDataURL(img);
$.ajax({
url: base_url + "server.php",
type: 'POST',
data: formData,
success: function(data) {
console.log(data);
if (data === "ok") {
getJson(data_url, file_name);
} else {
alert("something worng");
}
},
cache: false,
contentType: false,
processData: false
});
});
var pts;
function getJson(data_url, file_name) {
console.log(file_name);
var json_name = {
'name': file_name
};
$.ajax({
method: "POST",
url: base_url + "get_json.php",
crossDomain: true,
data: json_name,
dataType: 'JSON',
success: function(data) {
pts = data;
console.log(pts);
// alert(data_url);
}
});
}
once everything run good we get a json file with points . We can play what we want on canvas with these point. first you have to understand the whole process.
I am directly pasting my demo code here. Look the code and change what you want (like path, parameters... ) then run.
I am successfully get point details with these way for My virtual face make over project. I cant give you a my project url for your demo because project currently under process.
I have been looking at this problem for quite some time now.
My problem is simple, i want to send the filename along with the file, as a multipart request in Plupload, but i have not been able to do it yet.
I need the full filename of the uploaded file, so i can save the file with the right file extention, in this case it is images only.
Here is what i have until now (JavaScript part):
BeforeUpload: function(up, file) {
up.settings.multipart_params = {"name" : file.name, "gallery" : "9650f952-e397-11e5-8bca-d43d7e9e4e29"}
},
And in PHP i have this piece:
if (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} elseif (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} else {
$fileName = uniqid("file_");
}
$filearr = explode ($fileName);
$ext = array_pop ($filearr);
$withoutext = implode ($filearr);
So, how does i fix this mess?
I should have been paying more attention to the code.
I found 2 errors, it is both the explode and implode functions that are missing a parameter, so the answer is simply this:
$filearr = explode (".",$fileName);
$ext = array_pop ($filearr);
$withoutext = implode (".",$filearr);
I have problem with saving canvas image in PHP. I get a blank .png file. I search a lot about this problem but cant find anything useful about this. Why does it save a blank image instead of rendering real image?
JavaScript code:
html2canvas([document.getElementById('dadycool')], {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var image = new Image();
image.src = data;
document.getElementById('imagec').appendChild(image);
console.log(data);
$.ajax({
type: "POST",
url: "up.php",
data: {
imgBase64: data
}
}).done(function(o) {
console.log('saved');
});
}
PHP code:
<?php
// requires php5
define('localhost/samp/sample2/uploads', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I suspect you haven't configured your development box to display PHP error messages. You are defining a constant that is not a valid identifier:
define('localhost/samp/sample2/uploads', 'images/');
That means that you cannot use it directly:
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
... should be triggering:
Notice: Use of undefined constant localhost - assumed 'localhost'
Notice: Use of undefined constant samp - assumed 'samp'
Warning: Division by zero
Notice: Use of undefined constant sample2
Warning: Division by zero
Notice: Use of undefined constant uploads - assumed 'uploads'
Warning: Division by zero
... and file will only contain the base file name (e.g. 53676a01cdb59.png) but not path component. You need to use this syntax:
$file = constant('localhost/samp/sample2/uploads') . uniqid() . '.png';
... or, even better, give the constant a sensible name:
define('DIR_UPLOADS', 'images/');
I was having this same issue - it looked like the base64 data was being sent correctly but always failed to generate the image server side. The solution I found was to use the 'FormData' object and a very simple xhr request to post to the server.
var url='/path/to/save.php';
var data=oCanvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
var fd=new FormData();
fd.append('imgdata',data);
var request = new XMLHttpRequest();
request.open('POST', url);
request.send(fd);
I'm 99% sure the problem was caused by the incorrect Content-Type header being sent by the xhr request. Using a basic xhr request combined with FormData forced the xhr request to be sent with the multipart/formdata content type with correctly defined content boundaries.