Multiple files in to folder - javascript

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")

Related

Problem in uploading file in Folder in laravel 5.3?

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
}
}

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

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.

Codeigniter: write_file() returns false

public function ExportCSV()
{
// THIS PART IS WORKING
$this->load->dbutil();
$this->load->helper('file');
$delimiter = ',';
$newline = "\n";
$enclosure = '"';
$filename = "tamp.csv";
$query = "SELECT politician.id, politician.ident, party.abbr, politician.id_image, politician.name, politician.surname, politician.personal_birth, politician.home_city, politician.political_function
FROM politician
INNER JOIN party
WHERE party.id = politician.id_party
LIMIT 10000";
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline, $enclosure);
// data IS CORRECT
// THIS PART NOT WORKING: write_file() returns false
if ( ! write_file(APPPATH."/assets/media/upload/tamp.csv", $data, 'r+'))
{
echo 'Unable to write the file';
}
else
{
echo 'File written!';
}
}
The variable $data contains the correct output but the write_file() returns false.
The directory /assets/ is in the main directory of the codeigniter project.
My questions are:
Is this function returning false because I don't have the permission to write in this directory?
If yes, what should I do?
In which directory should I write this file as I would like it public?
When creating a file with write_file make sure your folder/directory is there where you would like to create file
Then I would recommend using FCPATH
$data = "Some file data";
if (write_file(FCPATH . '/document/text.txt', $data) == FALSE)
{
echo 'Unable to write the file';
} else {
echo 'File written!';
}
My directory
application
document
system
index.php

PHP Rename or Replace an uploaded file on user request using jquery and PHP

I am developing a PHP application in which I have to upload multiple files on the server, what I want is that when a user uploads multiple files the system should check if any of the files already exists, if yes then it should ask the user whether to rename the file or replace the older file,if user selects the rename option it should rename the file and if the user asks to replace the file it should do accordingly.
Untill Now I am using the following Code to upload the files:
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
// $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="../reztrictedfolder/dir1/";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(file_exists("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"../reztrictedfolder/dir1/".$file_name);
}else{ //rename the file if another one exist
//rename($file_tmp,$new_dir) ;
list($txt,$ext) = explode(".", $file_name);
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$new_dir="../reztrictedfolder/dir1/".$actual_image_name."_copy";
move_uploaded_file($file_tmp,$new_dir);
}
// mysql_query($query);
}else{
// print_r($errors);
}
But it only checks if the file already exists and rename it, but I want to let the user know that file already exists and if he wants to rename the file or replace the existing file..?
If you use AJAX so you sent from PHP response to JavaScript, which contains a list of file. I've use a function json_encode as parameters list of file. In javascript use JSON.parse()
HTML Section
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div id="submitbutton">
<button type="submit">Upload Files</button>
</div>
</fieldset>
</form>
JavaScript
function FileSelectHandler(e) {
var files = e.target.files || e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
UploadFile(f);
}
}
function ResponseParse(data) {
if (typeof data === "object") {
for (var i = 0, lng = data.files.length; i < lng; i++) console.log(data.files[i]);
}
}
function UploadFile(file) {
var xhr = new XMLHttpRequest();
// for example only jpeg file allowed
if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// Response from server
var data = JSON.parse(http.responseText);
ResponseParse(data);
}
}
xhr.send(file);
}
}
PHP
<?php
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
exit;
}
else {
$files = $_FILES['fileselect'];
$uploaded['files'] = array();
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
$uploaded['files'][] = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($uploaded);
}
This example working with XMLHttpRequest2. List of supported browser http://caniuse.com/#feat=xhr2. If you support old browser, you must old form-style upload or iframe upload idally by jquery, like this https://blueimp.github.io/jQuery-File-Upload/

Upload CSV file then Show Headings of columns

$org_file_name = $_FILES['file1']['name'];
$file_size = $_FILES['file1']['size'];
$ext = strtolower(pathinfo($org_file_name, PATHINFO_EXTENSION));
$file_path = 'docs/';
$rand = rand(111,999);
if($ext == 'csv')
{
if(file_exists($file_path))
{
$file_path = 'docs/'.$org_file_name;
}
if(!move_uploaded_file($_FILES['file1']['tmp_name'],$file_path))
{
die ('<script> alert("file not uploaded successfully."); </script>');
}
}
else
{
die ('<script> alert("Uploaded only CSV files."); </script>');
How Do I rename CSV file when uploading and insert into database with renam and after insert show csv column headings in buttons
CSV headers (if present) are located right on the first line. So you can simply do:
$delimiter = ',';
$headers = fgetcsv(fopen($file_path, 'r'), $delimiter);
if (is_array($headers)) {
foreach($headers as $header) {
echo "<input type=\"button\" name=\"$header\"
value=\"$header\"/>'";
}
}
}
And to rename the file while moving, you should change the second parameter of move_uploaded_file() to the desired name. If you like, you can get a unique ID using sha1_file($_FILES['file1']['tmp_name']). It will also avoid duplicated storage of identical files.

Categories