Send $_POST[] and $_FILES[] in same Ajax call - javascript

I am working on an image upload post part of my site and I am struggeling to be able to upload the image with the date. I am sending the date via $_POST and the files for the images in $_FILES.
Here is my code (Javascript):
(function post_image_content() {
var input = document.getElementById("images"),
formdata = false;
function showUploadedItem (source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
li.appendChild(img);
list.appendChild(li);
}
if (window.FormData) {
formdata = new FormData();
document.getElementById("btn").style.display = "none";
}
input.addEventListener("change", function (evt) {
var data = '';
date = document.getElementById('image_date').value;
if(date == ''){
alert('Please select a date!');
return 0;
} else {
data = 'date='+date;
}
document.getElementById("response").innerHTML = "Uploading . . ."
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("images[]", file);
}
}
}
if (formdata) {
$.ajax({
url: "submit_image.php",
type: "POST",
data: formdata + ' ' + data,
processData: false,
contentType: false,
success: function (res) {
$('#images').show();
document.getElementById("response").innerHTML = res;
hideImageUpload();
}
});
}
}, false);
}());
function hideImageUpload(){
$('#image_upload_form').hide(250);
//$('#response').hide(250);
$('#image-list').hide(250);
}
And the PHP:
<?php
require_once 'core/init.php';
$user = new User();
$errors = $_FILES["images"]["error"];
$date = $_POST['date'];
$date = explode("/", $date);
$newdate = $date[2] + '-' + $date[0] + '-' + $date[1];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
//$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = explode("_", $name);
$imagename='';
foreach($name as $letter){
$imagename .= $letter;
}
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" . $user->data()->id . '_' . $imagename);
$user->create('photos', array(
'osid' => $user->data()->id,
'user' => $user->data()->username,
'gallery' => 'Uploads',
'filename' => "images/uploads/" . $user->data()->id . '_' . $imagename,
'date' => $newdate
));
}
}
echo "<h2>Successfully Uploaded Images</h2>";
I am new to web development, and I am using PDO to enter into database.

Wait... data: formdata + ' ' + data, It is slightly confusing. You add FormData object and string containing url-encoded data.
Append date value to your formdata object: formdata.append('date', date). After this, send AJAX query with data: formdata, only.
But there may be more errors.
For debugging, use Chrome developer tools. You can use debugger and console.log(something) for breakpoint and printing your vars. Also, you always can use step-by-step debugging.

Related

Limit image upload size

I have a script for uploading images, it works fine but I would like to limit the image size to a maximum of 2 mb, I have tried a few things but without success, I am not one of the best at this so I would be very grateful for some help, follow the code
$(document).ready(function(){
$("#but_upload_w").click(function(){
var fd = new FormData();
var files = $('#file_w')[0].files;
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'host/profile/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#up-01").attr("value",response);
$("input").show(); // Link img
}else{
alert('failed');
}
},
});
}else{
alert("select");
}
});
});
<?php
if(isset($_FILES['file']['name'])){
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions)) {
if(move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newfilename)){
$response = "host/profile/upload/".$newfilename;
}
}
echo $response;
exit;
}
echo 0; ?>
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file() for more information.

save pdf edit to server using pdfannotate

I'm using the jsPDF plugin to create a pdf file. Currently, the method can generate a download file based on the click button. instead of that, I would like to save the file into the server when I click the button. a few research I use jquery.ajax to send the data to the file server.
Code
PDFAnnotate.prototype.savePdf = function() {
var inst = this;
var doc = new jspdf.jsPDF();
inst.fabricObjects.forEach(function(fabricObj, index) {
if (index != 0) {
doc.addPage();
doc.setPage(index + 1);
}
doc.addImage(
fabricObj.toDataURL({
format: 'png'
}),
inst.pageImageCompression == "NONE" ? "PNG" : "JPEG",
0,
0,
doc.internal.pageSize.getWidth(),
doc.internal.pageSize.getHeight(),
`page-${index + 1}`,
["FAST", "MEDIUM", "SLOW"].indexOf(inst.pageImageCompression) >= 0 ?
inst.pageImageCompression :
undefined
);
if (index === inst.fabricObjects.length - 1) {
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', baseurl + "wo/replaceFile", true);
xhr.send('pdf');
}
})
}
Based on xhr.open I call method in controller Wo.php/replaceFile()
if(!empty($_FILES['pdf'])) {
$data = $_POST['pdf'];
$fname = "test.pdf"; // name the file
$file = fopen("testa/pdf/" .$fname, 'w');
fwrite($file, $data); //save data
fclose($file);
} else {
throw new Exception("no data");
}
?>
But no action happened.

i want to save or download an image from blob url or data

im doing a paste event from clipboard, it creates a blob url. Now i dont how to save or get the file. How can i save it to my computer? I think im totally wrong in getting the blob in my php. im getting it as a string then trying to save it
This is my code for creating the blob
<?php
if( isset( $_FILES['file'] ) ) {
$file_contents = file_get_contents( $_FILES['file']['tmp_name'] );
header("Content-Type: " . $_FILES['file']['type'] );
die($file_contents);
}
else {
header("HTTP/1.1 400 Bad Request");
}
print_r($_FILES);
?>
<script type="text/javascript">
document.onpaste = function (e) {
var items = e.clipboardData.items;
var files = [];
for( var i = 0, len = items.length; i < len; ++i ) {
var item = items[i];
if( item.kind === "file" ) {
submitFileForm(item.getAsFile(), "paste");
}
}
};
function submitFileForm(file, type) {
var extension = file.type.match(/\/([a-z0-9]+)/i)[1].toLowerCase();
var formData = new FormData();
formData.append('file', file, "image_file");
formData.append('extension', extension );
formData.append("mimetype", file.type );
formData.append('submission-type', type);
var xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.open('POST', '<?php echo basename(__FILE__); ?>');
xhr.onload = function () {
if (xhr.status == 200) {
var img = new Image();
img.src = (window.URL || window.webkitURL)
.createObjectURL( xhr.response );
document.getElementById("nye").appendChild(img);
document.getElementById("nye").style.display = "none" ;
var x = document.getElementById("image");
x.setAttribute("type", "text");
x.setAttribute("value", img.src);
document.getElementById("image").appendChild(x);
}
};
xhr.send(formData);
}
</script>
This is my code that's save to my computer, it runs but i juts recive a blank jpg file
<?php
$data = $_POST['url'];
$filePath = $uploadDir . $name;
$contents_split = explode(',', $data);
$encoded = $contents_split[count($contents_split)-1];
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++) {
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
}
$fp = fopen('sample23.jpg', 'w');
fwrite($fp, $decoded);
fclose($fp);
?>
it saves but i think the file is blank.

Can't upload large files using XHR and FormData

I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile

Save base64 images with Ajax and Javascript

I'm trying to save/upload images with base64 decode via ajax and FileReader. Photos are displaying but no saving on specify destination. Can anybody help?
The code:
HTML
<input type="file" id="choose" multiple="multiple" />
JS
function readImage(file) {
var reader = new FileReader();
var image = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
var w = this.width,
h = this.height,
t = file.type,
n = file.name,
s = ~~(file.size/1024) +'KB';
$('#uploadPreview').append('<img src="'+ this.src +'"><br>');
};
image.onerror= function() {
alert('Invalid file type: '+ file.type);
};
};
}
$("#choose").change(function (e) {
if (this.disabled) return alert('File upload not supported!');
var F = this.files;
if (F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i] );
$.each(this.files, function(index, file) {
$.ajax({
url: "upload.php",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {}
});
});
files = [];
});
PHP
<?php
function uploadimg() {
$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();
$a=0;
unset ($_POST['action']);
foreach($_POST as $basefile){
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$base64_string = $basefile;
echo $basefile;
$base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string );
$decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
$source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
$output_file = $upload_path.'myfilef'.$a.'.jpg';
$images[]=$output_file;
$a++;
$image = fopen( $output_file, 'wb' );
$bytes=fwrite( $image, $source);
echo $bytes;
fclose( $image );
}
echo json_encode($images);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
?>
Thx for help.

Categories

Resources