I was following a tutorial about how to make an javascript/ajax upload system with progress (%) indicator . I have successfully added a css progress bar indicator to it .
But i have a problem that i can't solve is how to put to condition of upload like: type, file size, file is set, ....
here is my code (upload.php)
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
and this is the javascript file (upload.js):
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
I just need and example of how to check file size is less than 50MB and i can do the other checks my self i just don't know how to check condition in this upload system.
Thanks in advance
If you want to check something like the size, you can realize it with your code easily:
Take a look at these lines in your code:
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
This is where the files are added to the FormData which is then submitted to the server. You can add the conditions here, e.g. a size check:
for (var i = 0; i < fileInput.files.length; ++i){
//file.size is given in bytes
if(fileInput.files[i].size <= MAX_FILESIZE_IN_BYTES){
data.append('file[]', fileInput.files[i]);
}
}
I hope this helps.
Related
I'm having a weird issue I created an app to open PNG and PDF's. The problem is when I try to open PDF files larger than 2,000 Kb it will not display, however PNG's have no problem. I'm confused as too why this is.
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="styles.css">
</head>
<body>
<ul>
</ul>
<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="file-select[]" multiple="multiple">
<div id="filedrag" style="display: block;">or drop files here</div>
</div>
<div id="submitbutton" style="display: none;">
<button type="submit">Upload Files</button>
</div>
<div id="sortbutton">
<button type="submit">Submit</button>
</div>
<div id="resetbutton">
<button type="submit">Reset</button>
</div>
</fieldset>
</form>
<div id="messages">
</div>
<script src="filedrag.js"></script>
</body></html>
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("application") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<object data="' + e.target.result + '"></object></p>');
}
reader.readAsDataURL(file);
}
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" height="500px" width="500px"></p>');
}
reader.readAsDataURL(file);
}
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton");
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
As I said you try to post a PDF file larger than 2000 Kb it will not display, PNG however will display
I fixed it I hardcoded the path to display the Files
I had the same issue like yours and I resolved in this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>
I created a very basic example of a multiple file upload form (reference), it works perfect on desktop but not on mobile, at least the ones I am testing with.
On Mobile (Xiaomi Mi4 [Android version: 6.1] - Google Chrome/Mozilla Firefox): When I click on Choose files I see this screen:
If I choose Google Photos and select multiple files, only the first file will be inserted into the form.
If I select the Gallery (native) app and select multiple files I get the correct number on the form but when I click upload I get the "Aw Snap" screen:
Any idea why this is happening?
Besides Google Photos and the native app I tried 5 different apps, the last one, Piktures actually worked!
Please tell me this is not an app thing... is there a way to get the files correctly?
Code attached:
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
If you wish to test: http://odedta.com/projects/jqueryfileupload/
Thanks!
Try this might help you this is only front end part of file upload with js
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
I am not sure exactly about that mobile browsers are support multiple attribute I read some article it is not support or is not standart, any way If you want to post multiple image; You can see full code below
First Step;
You should use FileReader for load on browser as locally
Multiple file loading with FileReader
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
//Filename listing
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
//FileReader create and set onload event
var reader = new FileReader();
reader.onload = function (data) {
data.target.result;
}
//Read file
reader.readAsDataURL(input.files[x]);
}
}
Second Step
You can set image content to textarea as base64 data for each file
reader.onload = function (data) {
//....
//Split base64 data from DataURL (// "data:image/png;base64,.....)
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
//...
}
Third Step
Then you can send to your php file whole data and save your content as image
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
//decode base64 content and put file
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
Full Code
HTML & JavaScript
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple />
<form method="post" action="multipleFileUpload.php" enctype="multipart/form-data" id="formMultipleFileUpload">
<ul id="fileList">
</ul>
<input type="submit" value="Upload" id="btnUpload">
</form>
<script type="text/javascript">
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
var reader = new FileReader();
reader.onload = function (data) {
var li = document.getElementById('li_'+fileIndex);
var previewImg = document.createElement('img');
previewImg.setAttribute('width','50');
previewImg.setAttribute('height','50');
li.append(previewImg);
previewImg.src = data.target.result;
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
li.append(b64Input);
var fileName = document.createElement('input');
fileName.setAttribute('name','fileName[]');
fileName.value = input.files[fileIndex].name;
li.append(fileName);
fileIndex++;
}
reader.readAsDataURL(input.files[x]);
}
}
PHP (multipleFileUpload.php)
<?php
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
?>
Working screenshot
I am just trying to prototype a simple functionality using javascript for learning purpose, but the contents within the <p> tag are not updating and I am stuck at this point. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title> Ajax Search Box </title>
<script>
function LoadList()
{
var searchBox = document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
var xHttp = new XMLHttpRequest();
searchedChars += searchBox.value;
xHttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
var xmlContent = this.responseXML;
var nameList = xmlContent.getElementsByTagName("name");
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i].textContent + "<br/>";
}
resultBox.innerHtml = dispText;
}
};
xHttp.open("GET","AssessorList.xml",true);
xHttp.send();
}
</script>
</head>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">
No Data Available.
</p>
</body>
</html>
Could someone tell me why the innerHtml is not updating? Thanks in advance.
P.S: The code is fetching the data from the xml file as I could see in browser's console, the values being passed to the dispText variable.
<!DOCTYPE html>
<html>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">No data available</p>
<script>
function LoadList() {
var xhttp = new
XMLHttpRequest();
var searchBox =
document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
searchedChars += searchBox.value;
xhttp.onreadystatechange = function() {
//alert(this.status);
if (this.readyState == 4 && this.status == 200) {
var xmlContent = this.responseXML;
var nameList = searchedChars;
alert(nameList);
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i] + "<br/>";
}
resultBox.innerHTML = dispText;
}
};
xhttp.open("GET", "ajax.txt", true);
xhttp.send();
} </script>
</body>
</html>
Hope this may help you
I've some Javascript code. I included the jQuery file jquery-2.1.1.min.js and converted the whole Javascript code to jQuery code but when I executed this code I'm not able to POST the file. Due to which I'm not able to upload the file to the server using PHP. In firebug console I'm always getting blank. Can someone please help me in correcting this issue?
Original Javascript code :
<!DOCTYPE html>
<html>
<head>
<title>Take or select photo(s) and upload</title>
<script type="text/javascript">
function fileSelected() {
var count = document.getElementById('fileToUpload').files.length;
document.getElementById('details').innerHTML = "";
for (var index = 0; index < count; index ++) {
var file = document.getElementById('fileToUpload').files[index];
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('details').innerHTML += 'Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type;
document.getElementById('details').innerHTML += '<p>';
}
}
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('fileToUpload').files.length;
for (var index = 0; index < count; index ++) {
var file = document.getElementById('fileToUpload').files[index];
fd.append('myFile', file);
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "savetofile.php");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progress').innerHTML = percentComplete.toString() + '%';
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">
<div>
<label for="fileToUpload">Take or select photo(s)</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />
</div>
<div id="details"></div>
<div>
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progress"></div>
</form>
</body>
</html>
Converted above code to jQuery code as follows but getting blank in POST :
<!DOCTYPE html>
<html>
<head>
<title>Take or select photo(s) and upload</title>
<script type="text/javascript" charset="utf-8" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
function fileSelected() {
var count = $('#fileToUpload').get(0).files.length;//$('#fileToUpload').size() may also work
$('#details').html("");
for (var index = 0; index < count; index ++) {
var file = $('#fileToUpload').get(0).files[index];//.get(0) gives you the js DOM object
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
$('#details').append('Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type);
$('#details').append('<p>');
}
}
function uploadFile() {
var fd = new FormData();
var count = $('#fileToUpload').get(0).files.length;
for (var index = 0; index < count; index ++) {
var file = $('#fileToUpload').get(0).files[index];
fd.append('myFile', file);
}
$.ajax({url:"savetofile.php", type:'POST', success:uploadComplete, error:uploadFailed});
// abort is included in error, the second parameter passed to the error method would be statusText with value of abort in case of abort!
}
function uploadComplete(data) {
/* This event is raised when the server send back a response */
alert(data);
}
function uploadFailed(jqXHR, textStatus) {
if(statusText==="abort") {
alert("The upload has been canceled by the user or the browser dropped the connection.")
} else {
alert("There was an error attempting to upload the file.");
}
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">
<div>
<label for="fileToUpload">Take or select photo(s)</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />
</div>
<div id="details"></div>
<div>
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progress"></div>
</form>
</body>
</html>
Thanks in advance.
If you want I can give you the code of PHP file as well.
You're not passing any data, this is what you're doing
$.ajax({
url : "savetofile.php",
type : 'POST',
success : uploadComplete,
error : uploadFailed
});
that, sends nothing, you have to actually add the data
$.ajax({
url : "savetofile.php",
type : 'POST',
data : fd,
success : uploadComplete,
error : uploadFailed
cache : false,
contentType : false,
processData : false
});
I have been following a video tutorial on youtube for an AJAX upload, i know a fair amount of javascript, jquery, etc but this has me stumped.
my code is below, can anyone enlighten me as to why this is happening when i try to uploade more than one file or in some cases 1 file.
I have included my code below, its not perfect as i said i was follwoing along with a video tutorial.
<?php
if (!empty($_FILES['file']))
{
foreach($_FILES['file']['name'] as $key=>$name)
{
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'] [$key], "uploads/{$name}"))
{
$uploaded[] = $name;
}
}
if (!empty($_POST['ajax']))
{
die(json_encode($uploaded));
}
}
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="upload.js"></script>
</head>
<style type="text/css">
#upload_progress {display: none;}
</style>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded))
{
foreach ($uploaded as $name) {
echo '<div>'.$name.'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" multiple="multiple">
<input type="submit" id="submit" value="upload">
</form>
</body>
</html>
And my JS file is
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; ++i)
{
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes())
{
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert("Upload Failed");
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if (this.status == 200)
{
var links = document.getElementById('uploaded');
console.log(this.response);
var uploaded = JSON.parse(this.response);
var div, a;
for (var i = 0; i < uploaded.length; i++)
{
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'uploads/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log("error" + this.response);
}
}
});
request.open('POST', 'index.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
Initially the video had me using eval for the variable uploaded, i changed this to JSON.parse, i don't want a quick fix but rather an answer as to why this isn't working?
Thanks
Ben
I found out what the problem was, inside the php.ini file there is a size restriction on my server for file uploads, i increased that and it works fine now.
Anyone else who has the same problem check your upload size!