I'm trying to get working my upload script.
I'm using CodeIgniter, dropzone.js and Verot_upload class
form:
<form action="/admin/images/upload"
enctype="multipart/form-data" method="post"
class="dropzone"
id="my-awesome-dropzone"></form>
<script src="/skin/js/dropzone.js"></script>
and /admin/images/upload method
public function upload()
{
$data = array();
$this->load->library('verot_upload');
if ($this->authentication->is_loggedin())
{
if (!empty($_FILES))
{
// $tempFile = $_FILES['file']['tmp_name'];
$foo = new Verot_upload($_FILES['file']);
if ($foo->uploaded)
{
// save uploaded image with no changes
$foo->Process('./media/test/');
}
}
} else
{
redirect('/admin/login/', 'refresh');
}
}
it works with regular style:
function upload()
{
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';
$targetFile = $targetPath . $_FILES['file']['name'];
move_uploaded_file($tempFile, $targetFile);
// save data in database (if you like!)
}
}
But not with verot_upload.
So the issue was that, I was trying to upload image as in example at the class initialization.
if I initialize empty class and then use upload method everything works.
/**
* Method for uploading Images from dropdown form.
*
* #param $size
* #param $path
* #param $file
*/
public function upload_image($size, $path, $file)
{
$this->load->library('verot_upload');
$foo = new Verot_upload();
$foo->upload($file);
if ($foo->uploaded)
{
$foo->image_resize = true;
$foo->image_x = $size;
$foo->image_ratio_y = true;
$foo->Process($path);
if ($foo->processed)
{
$new_path = substr($foo->file_dst_pathname,1);
$this
->db
->set('date_created', 'NOW()', false)
->set('path', $new_path, true)
->insert('wysiwyg_img_uploads');
$foo->Clean();
}
}
}
Related
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<!DOCTYPE html>
<html>
<style>
.table_class{
display:none;
}
</style>
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
console.log(formData);
await fetch('file_ingest.php', {
method: "POST",
body: formData,
});
var test = document.getElementById("test");
test.innerText = ('The file has been uploaded successfully.');
//var returned_vals = JSON.parse(formData.responseText);
//console.log(returned_vals);
}
</script>
<body>
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<p id = "test"></p>
</body>
</html>
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<?php
set_time_limit(120);
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
$CSVfp = fopen("uploads/${filename}", "r");
if($CSVfp !== FALSE) {
while(! feoF($CSVfp)) {
$data = fgetcsv ($CSVfp, 1000, ",");
print json_encode($data);
//echo $data;
}
}
fclose($CSVfp);
<?php
set_time_limit(120); // if you need this you may have other problems
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
$response = [];
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
$response['status'] = 'Files Save Success';
// read the file here, if it failed the upload and move
// there is no point trying to read it
if (($fp = fopen($location, "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$response['data'][] = $data
}
fclose($fp);
}
} else {
$response['status'] = 'File Save Failure';
}
// now you can return either an error or a success and data
echo json_encode($response);
Now you need to checnge the javascript to look for the status in the right place and unload the row data from the the right place
I am trying to upload image in laravel but i am getting error when I am uploading image in folder, When I am uploading image and clicking on submit button, it's giving me problem in uploading file, i think there are error in this line...
move_uploaded_file($imageName, $moveable_file);
here are my usercontrolle.php file
public function dropzone(Request $request)
{
$user = Auth::user()->toArray();
$user_id = $user['id'];
$type = 'photo';
$type_id=0;
$data = $_FILES["image"];
//dd($data);
$doc_id = $_POST["doc_id"];
$doc_name = $_POST["doc_name"];
if($doc_id)
{ $img_id=$doc_id;
$img_name=$doc_name;
$response = $this->userService->deleteDocument($img_id,$img_name,$user_id,$type,$type_id);
}
// $image_array_1 = explode(";", $data);
// $image_array_2 = explode(",", $image_array_1[1]);
// $data = base64_decode($image_array_2[1]);
$storage_path = env('DOCUMENT_STORAGE_PATH');
$profile_upload_dir = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $storage_path);
if($type_id != '0'){
$destination_path = $profile_upload_dir . $user_id ."\\". $type."\\". $type_id;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}else{
$destination_path = $profile_upload_dir . $user_id ."\\". $type;
$destination_path = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path);
}
if(!is_dir($destination_path)) {
mkdir($destination_path, 0777,true);
}
$imageName = time() . '.png';
// dd($imageName);
$moveable_file = str_replace(["/","\\"], [DIRECTORY_SEPARATOR,DIRECTORY_SEPARATOR], $destination_path.'\\'.$imageName);
//dd($moveable_file);
move_uploaded_file($imageName, $moveable_file);
// file_put_contents($moveable_file, $data);
//$image_file = addslashes(file_get_contents($moveable_file));
$user = Auth::user()->toArray();
//dd($user);
$user_id = $user['id'];
$type_id = 0;
if(isset($photo['type_id']) && !empty($photo['type_id'])){
$type_id = $photo['type_id'];
}
//$photo['file']=$_FILES['photoimg'];
$photo['type']='photo';
$result = $this->userService->storeUserDocuments($imageName, $photo['type'], $type_id, $user_id);
// echo '<img src="data:image/png;base64,'.base64_encode($data).'" data-action="zoom" class="pull-left" style="height: 130px;width:130px;">';
}
You can also use image intervention to upload images.
First, install this on your laravel project using
composer require intervention/image
After installation open config/app.php and then add these in the $providers array.
Intervention\Image\ImageServiceProvider::class
Also, add the facade of this package to the $aliases array.
'Image' => Intervention\Image\Facades\Image::class
After this, you are ready to add images
Add this to your controller
use Intervention\Image\Facades\Image;
Here is a sample example of how to add images, use this in the controller
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension(); //use time to create file name
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
//Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('/images/'.$filename) );
$user->avatar = $filename;
// $user->save(); //To save the name of the file in the database
}
}
I'm using DropzoneJS to upload my images. So what I do is to take the base64URL generated by dropzoneJS, and then try to upload as follows:
$( document ).ready(function() {
var endpoint= $("#endpoint").val();
var unit = {
name: '',
description: '',
image: '',
base64Image: '',
themes: []
}
$("#create-unit-btn").on("click", function() {
unit.name = $("#create-name").val();
unit.description = $("#create-description").val();
unit.base64Image = $('#imageDropzone')[0].dropzone.files[0].dataURL;
var data = {
'_token': $('meta[name=csrf-token]').attr('content'),
'unit': unit
}
console.log(data);
$.ajax({
type: "POST",
url: endpoint,
data: data,
success: function(result){
console.log(result);
}
});
});
function validate() {
}
});
Then to upload the Image I use the following code:
public function create( Request $request ) {
$data = [];
$code = 200;
try {
$unit = new Unit();
$unit->name = request()->input('unit.name');
$unit->description = request()->input('unit.description');
$url = ImageHandler::StoreBase64ToFile($request->input('unit.base64Image'));
$unit->image = $url;
$unit->save();
$data['unit'] = $unit;
} catch ( \Illuminate\Database\QueryException $e ) {
// There was an error
$code = Response::HTTP_UNPROCESSABLE_ENTITY;
$data = [];
$data['error'] = ErrorResponse::create($code, $e->getMessage());
} catch( ModelNotFoundException $e ) {
return response()->json(['error' => 'invalid operation'], 406);
}
return response()->json($data, $code);
}
The ImageHandler class does the following:
<?php
namespace App\Libraries;
use Storage;
class ImageHandler {
/**
* Store a base64 image into the file system this data has to be
* sended without any header info like:
* data:image/png;base64
* So the info will look something like iVBORw0....hEUgAAAcQ==
* #param string $base64Data information
* #param string $filename the filename if not defined then it generates
* a random name
* #param string $disk disk location, check Storage documentation of
* laravel, by default is stored on the public folder
* so you'll have to run
* php artisan storage:link
* to make the symbolink links
* #return string url location of the file
*/
public static function StoreBase64ToFile($base64Data,
$filename = null,
$disk = 'public')
{
if (strlen($base64Data) < 10) {
return null;
}
$image = base64_decode($base64Data);
if ($filename == null) {
$filename = str_random(16);
$filename .= '_'.time();
$filename .= '.png';
}
$path = 'images/'.$filename;
$result = Storage::disk($disk)->put($path, $image, 'public');
if ($result) {
$url = Storage::disk($disk)->url($path);
return $url;
}
return null;
}
}
But when I upload the image, even that the process ends correctly, when I try to open the file from my file browser (finder on MacOs), I can't see the uploaded image. I mean the file it’s there but I cant see the content of the image
I don't know why is not been uploaded correctly.
It was an error of format when I stored the Image. In order to upload the file without any problem I had to do the following before send the request: unit.base64Image = unit.base64Image.replace("data:image/png;base64,", "");
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.
Hello I have a view file and controller, what makes multiple inputs where I can upload files in to folder, but its uploading only one file in to folder. I know what is problem, but I dont know how to fix this or how to do this.
My Controller:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data['files'];
//print_r($this->data['files']); die;
if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($uploadData['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
My View file:
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[files]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
And this script what Im using in View :
$(document).ready(function() {
var max_fields = 3;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
I think that, the problem is in input names. If Im doing more inputs, then the inputs names are same, and thanks to this its uploading only one file in to webroot/files folder, but I want these all.
Can anybody help me or give me some tips.
Thanks !
Here is someone with almost exactly the same issue as you have:
Create multiple Upload File dynamically
Try doing the same. I haven't programmed PHP for quite some time, but I guess you should replace data[files] to just data[], so it creates a new array item for each field. Now you are giving each field the same name.
Then you can loop over them in your controller by using:
foreach($_FILES['data'] as $file){
//do stuff with $file
}
EDIT 2:
As you are saying, you want to upload the files (not to a db). So I guess this should work:
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
echo "Failide maht kokku ei tohi olla üle 5MB";
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $file)) {
return false;
}
echo "Sa sisestasid faili(d): $filename";
}
}
}
Try this function:
function multi_upload($file_id, $folder="", $types="") {
$all_types = explode(",",strtolower($types));
foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
if(!$_FILES[$file_id]['name'][$key]){
$return[$key]= array('','No file specified');
continue;
}
$file_title = $_FILES[$file_id]['name'][$key];
$ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
$ext = strtolower($ext_arr); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,5);
$file_name = $uniqer . '_' . $file_title;//Get Unique Name
if($types!=''){
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
$return[$key]= array('',$result);
continue;
}
}
//Where the file must be uploaded to
if($folder) $folder .= '/';//Add a '/' at the end of the folder
$uploadfile = $folder . $file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
}
else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
}
else {
#chmod($uploadfile,0777);//Make it universally writable.
}
}
$return[$key]=array($file_name,$result);
}
return $return;
}
html: <input type="file" name="data_file[]" id="uploadFilefiles">
Call by multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")