Angular + PHP file upload (can't sent newly created properties) - javascript

I'm using ng-file-upload
.
It works perfectly, But I need to add some specific properties to object that I sent. Here controller method:
self.uploadFiles = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
files[i].upload_folder = 'upload'; //here i add first property
files[i].current_date = getCurrentDate(); //here second
var file = files[i];
console.log(files[i]);
Upload.upload({
url: 'app/views/antonovich/upload.php',
headers: {'Content-Type': undefined},
method: 'POST',
data: file,
file: file
}).progress(function(evt){
self.uploadProgress = parseInt(100.0 * evt.loaded / evt.total);
//console.log('progress: ' + self.uploadProgress + '% ' + evt.config.file.name);
}).success(function(data, status, headers, config){
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
$('.errors').html(data);
self.uploadReady = config.file.name + ' uploaded.';
});
}
}
}
In console log I see that properties, for example:
File {$$hashKey: "object:19", upload_folder: "upload", current_date: "2016-01-08"}
$$hashKey: "object:19"
current_date: "2016-01-08"
file: File
lastModified: 1448878298580
lastModifiedDate: Mon Nov 30 2015 13:11:38 GMT+0300 (Russia Standard Time)
name: "14488072165280.png"
size: 872713
type: "image/png"
upload_folder: "upload"
webkitRelativePath: ""
__proto__: File
PHP script uploads these files to folder and creates DB row, But 2 created properties are undefind, and return just this:
Response: Array
(
[name] => 14488072165280.png
[type] => image/png
[tmp_name] => C:\wamp\tmp\phpC39D.tmp
[error] => 0
[size] => 872713
)
here php script example:
<?php
if(isset($_FILES['file'])) {
print_r($_FILES['file']);
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_type = $_FILES['file']['type'];
$upload_folder = $_FILES['file']['upload_folder'];
$current_date = $_FILES['file']['current_date'];
print_r($upload_folder);
print_r($current_date);
$db = new PDO('mysql:host=localhost;dbname=antonovich', 'root', '');
$query = "INSERT INTO portfolio(url,date) VALUES('$file_name','$current_date')";
$stmt = $db->prepare($query);
$stmt->execute();
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
move_uploaded_file($file_tmp,"../../img/".$upload_folder."/".$file_name);
echo $file_name . " uploaded file: " . "images/" . $file_name;
}
else {
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>

For background, see PHP documentation on file uploads. The $_FILES superglobal only contains a fixed set of values about each uploaded file (name, type, tmp_name, error, and size), any other data from the POST request should be in the $_POST superglobal instead. Try changing your PHP script like so:
$upload_folder = $_POST['upload_folder'];
$current_date = $_POST['current_date'];
As a side note, I would be wary about allowing clients to specify the destination folder without robust validation. Attackers might be able to use relative paths to upload malicious code.

Related

Unable to upload image using axios in React with PHP

I am working on Reactjs and Php, Actually i am trying to upload image to server, Image is uploading but whenever i try to open image then showing "we dont support this file format", How can i fix this ?
I am sending formdata with multipart form data and in php (api) i am using base64 image for upload image to server
Is my apporach for sending image to axios (api) is correct or something wrong with php code
Here is my nextjs code
const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
var imagefile = document.querySelector('#file');
formData.append("file", imagefile.files[0]);
const response = await axios({
method: "post",
url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
}).then(function (response) {
alert('respone is '+ response.data.msg);
}).catch(function (error) {
alert('respone is '+ error);
console.log("failed to get recommend playlist");
console.log('error is '+ error.msg);
});
}
And following is my Api code in Php side
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode(explode( ',', $files)[1]);
define('UPLOAD_DIR', 'uploads/');
$file_ext = strtolower( end(explode('.',$file_name)));
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.'.$file_ext;
file_put_contents($file, $image_base64);
The issues is from the PHP. You can just simplify it by using pathinfo() to get the extension and move_uploaded_file() to move the uploaded file to the server.
Try this
define('UPLOAD_DIR', 'uploads/');
$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$file_name = UPLOAD_DIR . uniqid() . time() . '.' . $file_ext;
move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);

jQuery - Append file name to FormData and get it in a PHP script

I have the following JS code that I use to upload an image based on its path:
var data = new FormData();
data.append('fileName', fileName);
data.append('file', file);
$.ajax({
url : dbPath + "upload-file.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
This is my upload-image.php script:
<?php
$fileName = $_POST['fileName'];
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "Sorry, your file is larger than 20 MB. Upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr."".$fileName;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
Everything works fine in a matter of uploading a file, a JPG image for example, but my purpose is to use:
data.append('fileName', fileName);
to simply append the file name and extension to my FormData and get a file URL like this:
https://example.com/_json/uploads/03aC8qsIk4hanngqO3G4_fileName.jpg
But the $fileName variable in my PHP script fires an error_log line as Undefined index fileName in line xx, so is there a way to upload a file, get its name and extension and append it to the file URL that my PHP script generates?
I hope my question is clear, what I'm trying to do is simply a general Ajax automatic upload for any kind of file, not just images, and get their URL based on a random string + its name and extension (like .png, .mp4, .pdf, etc.).
I've figured it out, thanks to all the comments, I had to append the fileName to my FormData() and edit my PHP script as it follows:
JS:
function uploadFile() {
var dbPath = '<?php echo $DATABASE_PATH ?>';
var file = $("#file")[0].files[0];
var fileName = file.name;
console.log('FILE NAME: ' + fileName);
Swal.fire({icon: 'success', title: 'Loading...', showConfirmButton: false })
var data = new FormData();
data.append('file', file);
data.append('fileName', fileName); <!-- ADDED THIS LINE
$.ajax({
url : dbPath + "upload-file.php?fileName=" + fileName, <!-- ADDED THIS LINE
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data", <!-- ADDED THIS LINE
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
// error
if (data.includes("ERROR:")) {
Swal.fire({ icon: 'error', title: 'Oops...', text: data, });
// show file data
} else {
$("#fileURL").val(fileURL);
$("#viewButton").attr("href", fileURL);
$("#viewButton").css("display", "block");
}
// error
}, error: function(e) {
Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong: ' + e.message, });
}});
}
My upload-file.php script:
<?php include 'config.php';
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString."_".$_POST['fileName']; <!-- ADDED THIS LINE
}
?>
Now I can finally upload any type of file and get its name + extension at the end of the URL, it works perfectly.

Trouble sending an generated jsPdf to server

I have generated an PDF using jsPdf and Html2Canvas. It works very well, and is downloadable.
I'm now aiming to get the generated .pdf saved to my server, so I can send it out via phpmailer. This is how I approached this.
function print() {
document.getElementById("out").textContent = document.getElementById("fader").value;
const filename = 'DHC_Herren_Front.pdf';
html2canvas(document.querySelector('#pdf')).then(canvas => {
let pdf = new jsPDF('l', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211, function () {
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax('/st/tda/dhc/men_front/upload.php', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data)
},
error: function (data) {
console.log(data)
}
});
});
});
}
and my upload.php
<?php move_uploaded_file(
$_FILES['pdf']['tmp_name'],
$_SERVER['DOCUMENT_ROOT'] . "/st/tda/dhc/men_front/test.pdf");
?>
My Question would be, why I end up without an File on the Server. I feel like there must be an simple solution to this, but I just can't pinpoint it.
Newest HTML
function ma() {
document.getElementById("out").textContent = document.getElementById("fader").value;
html2canvas(document.querySelector('#pdf')).then(canvas => {
var pdf = btoa(doc.output());
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211,);
$.ajax({
method: "POST",
url: "/st/tda/dhc/men_front/upload.php",
data: {data: pdf},
}).done(function(data){
console.log(data);
});
});
}
Newest upload.php
<?php
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
// print_r($data);
file_put_contents( "test.pdf", $data );
} else {
echo "No Data Sent";
}
exit();
This is how I do it. Take a look and see if you can adapt it to your code. This is the uploadFiles.php that the ajax sends the file to.
<?php
$ds = DIRECTORY_SEPARATOR; // a directory separator
$cid = $_POST["cid"]; // directory name passed from the form as a variable
$rid = $_POST["rid"]; // directory name passed from the form as a variable
$storeFolder = "../recordFiles/".$cid."/".$rid; // the place where i want to save stuff
// run only if there are files sent from ajax.
if (!empty($_FILES)) {
// check if the directory exists and if not then create it.
if (!file_exists('../recordFiles/'.$cid."/".$rid)) {
mkdir('../recordFiles/'.$cid."/".$rid, 0777, true);
}
// get the temp file name
$tempFile = $_FILES['file']['tmp_name'];
// remove all whitespace in the file name
$cleanedFileName = $_FILES['file']['name'];
$cleanedFileName = preg_replace('/\s+/', '', $cleanedFileName);
// set the target path
$targetPath = dirname( __FILE__ ).$ds.$storeFolder.$ds;
// set the target file name and path
$targetFile = $targetPath.$cleanedFileName;
// move the files
move_uploaded_file($tempFile,$targetFile);
}
?>

Dlib for javascript

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.

How to use the extra params in ExtJS Upload Widget by Ivan Novakov

I am using this upload widget in my web application.
I am using the FormDataUploader and I am able to upload files to a server directory quite well. However, I wanted to send extra parameters as well to the php file handling the upload. This is what I attempted:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploader : 'Ext.ux.upload.uploader.FormDataUploader',
uploaderOptions : {
url : 'uploadGallery.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
As you can see, I used the uploadParams, however, my PHP couldn't seem to receive it. In my php file, I have:
$ID_Person = $_GET['ID_Person'];
$ID_CI = $_GET['ID_CI'];
However, my PHP seems to be unable to get these params.
What I did next was to use the default ExtJS Uploader as such:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
At first, I used the old PHP file which was able to get the extra params I sent. However, it seems that I needed to use a different PHP file for the ExtJS uploader.
This is what my PHP file looks like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
require __DIR__ . '_common.php';
$config = require __DIR__ . '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
// $outputFilename = $config['upload_dir'] . '/' . $fileName;
$outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response();
However, I am getting an Internal Server 500 Error - Meaning that there was something probably wrong with my php file.
I mainly have two questions:
How do I make the uploadParams work with the FormDataUploader?
How do I write a PHP uploader for an ExtJS Data Uploader?
Got it to work.
The uploadExtJS.php file should look like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
// require __DIR__ . '_common.php';
// $config = require __DIR__ . '_config.php';
require_once '_common.php';
$config = require_once '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
$outputFilename = $config['upload_dir'] . '/' . $fileName;
// $outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response(true, "okay");
_common.php looks like:
<?php
function _log($value){
error_log(print_r($value, true));
}
function _response($success = true, $message = 'OK'){
$response = array(
'success' => $success,
'message' => $message
);
echo json_encode($response);
exit();
}
function _error($message){
return _response(false, $message);
}
_config.php should look like:
<?php
return array(
'upload_dir' => 'gallery',
'fake' => false
);
?>
and now I'm working on using a unique name using uniqid() and microtime(), as well as saving the images to a subdirectory (or any folder under your main upload/gallery folder) using the uploadParams() property.
EDIT 1: RENAMING THE UPLOADED FILE
just change this line:
$fileName = htmlspecialchars($fileName);
to:
$fileName = uniqid() . '_' . microtime();
EDIT 3: TO GET THE CUSTOM SUB DIRECTORY FROM YOUR ADDITIONAL PARAMS
First, make sure than when you create your Upload Dialog from your ExtJS web app, you do this:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_1 : ID_1,
ID_2 : ID_2 // you can put waaay more if you want
}
});
and in your uploadExtJS.php, do this (between the part where you define your new file name and the part where you check for input stream)
$fileName = uniqid() . '_' . microtime();
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$ID_1 = $_GET['ID_1'];
$ID_2 = $_GET['ID_2'];
$newFilePath = $config['upload_dir'] . '/' . $ID_1 . '/' . $ID_2;
if (!file_exists($newFilePath)) {
mkdir($newFilePath, 0777, true);
}
$inputStream = fopen('php://input', 'r');
$outputFilename = $newFilePath . '/' . $fileName;
$realSize = 0;
$data = '';
As you can see, I defined a $newFilePath variable, checked if it was existing before making it, then uploaded to that directory.
Hope this helps anyone who encounters the issue in the future.

Categories