How to Upload a Full Folder with their files - javascript

I got this code for Upload multiple files but now I don't know how can I upload a folder with multiple files and maybe subfolder with more files. etc
As you can see I'm using javscript for getting and php for procesing and saving the files right now with files around 2MB
I was trying to get like $_Folder with a foreach but it doesn't work for me :/
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload Files</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script src="upload.js"></script>
</body>
</html>
process.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
upload.js
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
Expecting to Upload something like this
Upload:
-(1Folder)
--Image.png
--Imagen.jpg
--(2Folder)
---Image2.png
--(3Folder)
---Image3.jpg
--Imagen.gif

In modern Chrome, Firefox, and Edge you can set a html attribute, webkitdiretory to let the file input become a directory select window instead. And if you also use the multiple attribute after selecting the folder all contents (and contents in subfolders) will be in the .files list
<input type="file" webkitdirectory multiple>
You would then just use the same code to include all the files for upload.
Now if you want to keep the folder structure you would have to also include the webkitRelativePath which holds the relative path for that file within the folder you selected. And use that path to create the folders on the server.
for (let i = 0; i < files.length; i++) {
let file = files[i];
let fileParamName = `file${i}`;
let filePathParamName = `filepath${i}`;
formData.append(fileParamName, file);
formData.append(filePathParamName,file.webkitRelativePath);
}
And then on the server use filePathParamName to make the directory structure and move the file to it:
//Just for example
//make sure to used sanitized data in production
$folderpath = $path.dirname($_POST["filepath23"]);
$file = $path.$_POST["filepath23"];
$file_tmp = $_FILES["file23"]["tmp_name"];
//third option is for recursive folder creation (make subfolders)
mkdir($path,0644,true);
move_uploaded_file($file_tmp, $file)
For an easier method you could put all the files into a zip file within javascript and just upload the single zip file and extract on the server. Using JSZip and PHP ZipArchive class:
var zip = new JSZip();
for (let i = 0; i < files.length; i++) {
let file = files[i];
zip.file(file.webkitRelativePath, file);
}
zip.generateAsync({type:"blob"})
.then(function(content) {
formData.append("folderzip",content);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
Then in php unzip the folder to where you want it:
move_uploaded_file($file_tmp, $path);
$zip = new ZipArchive();
if($zip->open($path)){
$zip->extractTo($somepath);
$zip->close();
//delete zip file
unlink($path);
}
Client side demo of file listing using webkitRelativePath:
var output = document.querySelector("#output");
document.querySelector("input").onchange = function() {
var files = this.files;
for (file of files) {
output.insertAdjacentHTML('beforeend', `<div>${file.webkitRelativePath}</div>`);
}
}
<input type="file" webkitdirectory multiple>
<div id="output"></div>

Related

Multiple images upload using javascript, PHP, MySQl

Here I am doing a Hybrid Android app conversion. My page is HTML page. I need to upload multiple images using Javascript only. In my page I can't use PHP if(isset($_POST['submit'])) function because it's a HTML page. And also I can't use <form action='upload.php' method='POST'>, because it redirect to that PHP page. So I can't be in a same page.
<form method="POST" action="" id="proinsert" name="proinsert" enctype="multipart/form-data">
<input type="file" name="photo" id="photo" class="form-control">
<button id="submit" name="submit" class="btn btn-primary margintop">Submit</button>
</form>
and my PHP page
foreach($_FILES['photos']['name'] as $file){
$message .= "Attachments:" .$file['filename'];
}
Your question is very broad. However, I'll do my best to answer it:
You have 3 logical layers to your problem here:
The HTML that creates the user interface
The Javascript - that handles processing and sending your images (or any file) to another place.
Your PHP code, which will accept your images and process/save them to your server.
A brief overview of how to approach the solution:
Build a form in HTML with a file upload field.
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
In your HTML file, write or include Javascript that will serialise the form data, and POST it to your PHP file.
<script type="text/javascript">
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
// Uses browser's built in Fetch API - you can replace this with jQuery or whatever you choose.
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
Write the logic into a new PHP file (called process.php) to handle the form data (images) as appropriate.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
$fileNames = [];
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$fileNames[] = $file_name;
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) {
print_r($errors);
} else {
print_r(json_encode(['file_names' => $fileNames]));
}
}
}
For speed - the example code in this solution was taken from https://www.taniarascia.com/how-to-upload-files-to-a-server-with-plain-javascript-and-php/
For other examples - you could check out StackOverflow's other questions. Here's a similar one to yours: uploading image using javascript

How to save the image(uploaded from Dropbox Chooser) to the folder?

I know you think this as a silly question. But I am not able to get it done. I am using dropbox chooser to upload the images form user's dropbox account. Once they upload it, I am able to save it in the database, but I am not able to save it in the uploads folder. Following is my code:
Index.php
<form class="form" method="post" enctype="multipart/form-data" >
<div id="dropbox-container"></div>
<input id="dropbox_image" name="image" type="hidden" />
<button type="submit" class="button">Save</button>
</form>
<script type="text/javascript" src="https://www.dropbox.com/static/api/2/dropins.js" id="dropboxjs" data-app-key="wgiv8kvzvq57mlw"></script>
<script type="text/javascript">
options = {
success: function(files) {
files.forEach(function(file) {
add_img_to_list(file);
document.getElementById('dropbox_image').value = file['name'];
});
},
cancel: function() {
//optional
},
linkType: "preview", // "preview" or "direct"
multiselect: true, // true or false
extensions: ['.png', '.jpg'],
};
var button = Dropbox.createChooseButton(options);
document.getElementById("dropbox-container").appendChild(button);
function add_img_to_list(file) {
var li = document.createElement('li');
var a = document.createElement('a');
a.href = file.link;
var img = new Image();
var src = file.thumbnailLink;
img.src = src;
img.className = "th"
document.getElementById("img_list").appendChild(li).appendChild(a).appendChild(img);
}
</script>
hController.php
<?php
$fileName = $_POST['image'];
$tmpName = $_POST['image'];
$image = new \Model\Upload_Picture();
$image->image = $_POST['image'];
$fileName = uniqid()."_".basename($fileName);
$fileName = str_replace(' ', '_', $fileName);
$fileName = str_replace('-', '_', $fileName);
move_uploaded_file(tmpName, UPLOAD_PATH . 'pictures/'. $fileName );
$image->save();
?>
This code helps me to save the image into the database, but not storing it in the upload folder. I think I am making a mistake in some piece of code, help will be appreciated. Also if I upload multiple images from the dropbox account, I am not able to store all of them in my database. Only the last one is stored in db.

Multiple file upload in each inputs using CodeIgniter and Ajax with multiple input field

I am not able to upload multiple images in a folder in codeigniter. I have used this reference Multiple image upload. Someone please help me. Atleast the author of this reference please help me to sort out this problem. Here is my code
View
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
Script
$(document).ready(function(){
$('#save').on('click', function(){
var fileInputs = $('.file_input');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 ){
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
}
});
$.ajax({
url: '<?php echo base_url(); ?>exerciseset/process',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
method: 'post',
success: function(response){
console.log(response);
}
});
});
});
Controller
public function process()
{
$fileuploadurl = base_url() . "study_set/";
$config['upload_path'] = 'study_set/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp|mp3|mp4';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '25000000';
$F = array();
$count_uploaded_files = count( $_FILES['images']['name'] );
$files = $_FILES;
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES['userfile'] = [$files['images']['name'][$i]];
$F[] = $_FILES['userfile'];
// Here is where you do your CodeIgniter upload ...
$this->load->library('upload', $config);
$this->upload->data($_FILES['userfile']);
if (!$this->upload->data('images')) {
echo $this->upload->display_errors();
}
}
echo json_encode($F);
}
It returns the images name into array but not able to upload it into folder. And also i need each image name in separate variable. Please help me i am in hurry.
In your code it seems like you missed to upload file. Hence it will not moved to specific folder. Please check below, Hope it will help you.
public function process()
{
$fileuploadurl = base_url() . "study_set/";
$config['upload_path'] = APPPATH . 'uploads/study_set/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp|mp3|mp4';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '25000000';
$F = array();
$count_uploaded_files = count( $_FILES['images']);
$result = array();
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES["file"]["name"] = $_FILES["images"]["name"][$i];
$_FILES["file"]["type"] = $_FILES["images"]["type"][$i];
$_FILES["file"]["tmp_name"] = $_FILES["images"]["tmp_name"][$i];
$_FILES["file"]["error"] = $_FILES["images"]["error"][$i];
$_FILES["file"]["size"] = $_FILES["images"]["size"][$i];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$result['errors'][] = $this->upload->display_errors();
}else{
$result['success'][] = $this->upload->data();
}
}
echo json_encode($result);
}
Please make sure you have specified correct folder path and folder has enough permissions to write files.
Let me know if it not works.

Multiple file upload and zip them on the fly failed

I have created multiple file uploader using html & php. Uploader functionality works fine but while I try to create a ZIP on the fly in order to add uploaded file into ZIP file. In that case, failed to create zip and add uploaded file into zip. I don't know why it's not working.
Please check my scripts below and let me know if I missed anything thanks in advance:
Html scripts:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Upload with Progress Bar</title>
<script type="text/javascript">
// select file function only for styling up input[type="file"]
function select_file(){
document.getElementById('image').click();
return false;
}
</script>
</head>
<body>
<div class="container">
<!--status message will appear here-->
<div class="status"></div>
<!--image upload form-->
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a file</a>
<input id="image" type="file" multiple="multiple" name="files[]" >
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
</div>
</body>
</html>
Php Scripts:
header('Content-type: application/json');
$path = 'uploads/'; // upload directory
if (!file_exists('uploads')) {
mkdir('uploads', 0777, true);
}
$max_file_size = 1024*10000; // 1024 byte= 1kb 1024*100 byte=100kb
$count = 0;
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
$zip_path = 'download.zip';
$zip = new ZipArchive();
if ($zip->open($zip_path, ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ("An error occurred creating your ZIP file.");
}
foreach ($_FILES['files']['name'] as $f => $name) {
$filename = $_FILES['files']['name'][$f];
$filecontent = file_get_contents($_FILES["files"]["tmp_name"][$f]);
$filetype = $_FILES['files']['type'][$f];
$filesize = $_FILES['files']['size'][$f];
$fileext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);;
$zip->addFromString($filename, $filecontent);
//$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');
if ($_FILES['files']['error'][$f] == 4) {
$status[] ='Upload Fail: Unknown error occurred!';
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$status[] = "$name is too large!.";
continue; // Skip large files
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name)){
$count++; // Number of successfully uploaded file
$status[] = 'Image successfully uploaded!';
}
else {
$status[] = 'Upload Fail: Unknown error occurred!';
}
}
}
}
$zip->close();
}
else {
$status[] = 'Bad request!';
}
echo json_encode(array('status' => $status));
It's not working probably download.zip file doesn't exist in your directory.
Could you please create download.zip file or replace your following code then try again:
if ($zip->open($zip_path,ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}
With
if ($zip->open($zip_path,ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE)
{
die ("An error occurred creating your ZIP file.");
}

How to receive & process data sent to php with XMLHttpRequest?

I'm working on upload form for mp3 files and I hit a wall :/. Can you help please?
Here is my HTML:
<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div>
Here is my JavaScript:
function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');
uploadButton.innerHTML = 'Uploading...';
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('mp3file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php/commercial/upload.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Upload';
}
else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
}
And lastly my PHP:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['filename']['name']);
if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['filename']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
I'm trying to upload mp3 files to my server and sort them in folders, form validation is going ok, request doesn't return any errors and it seems my php code is not doing what it should be, I know i can do it with submit button without using JavaScript but i need to do it this way. So if any of you have any idea i would be very thankful.

Categories

Resources