Drag file upload, error in $_FILES - javascript

I try to create simple "drag&drop" file upload. This my code:
HTML (index.html):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="script.js"></script>
<form action="upload.php">
<div id="dropZone">
Drag File
</div>
</form>
JavaScript (script.js):
$(document).ready(function() {
var dropZone = $('#dropZone'),
maxFileSize = 1000000;
dropZone[0].ondrop = function(event) {
event.preventDefault();
dropZone.removeClass('hover');
dropZone.addClass('drop');
var file = event.dataTransfer.files[0];
if (file.size > maxFileSize) {
dropZone.text('Max size 1mb!');
dropZone.addClass('error');
return false;
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = stateChange;
xhr.open('POST', 'upload.php');
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
alert(xhr.responseText);
};
function uploadProgress(event) {
var percent = parseInt(event.loaded / event.total * 100);
dropZone.text('Loading: ' + percent + '%');
}
function stateChange(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200) {
dropZone.text('Ok!');
} else {
dropZone.text('Error!');
dropZone.addClass('error');
}
}
}
});
PHP (upload.php):
<?php
$uploaddir = 'upload/';
$uploadfile = $uploaddir.basename($_FILES['file']['name']);
if (!$_FILES)
{
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}
?>
My problem is that file can't upload in folder, $_FILES['file']['tmp_name'] is empty...
Does anybody have an idea, where my mistake?
thank you...

Try this, Change your condition
if (isset($_FILES['file']))
{
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}

Related

Unable to upload XMLHttpRequest file

Good afternoon to all users. Recently faced a file transfer problem. And along with the task, a bunch of problems appeared: There is a js code like this:
let dropArea = document.getElementById("drop-area")
;['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false)
document.body.addEventListener(eventName, preventDefaults, false)
})
;['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false)
})
;['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false)
})
dropArea.addEventListener('drop', handleDrop, false)
function preventDefaults (e) {
e.preventDefault()
e.stopPropagation()
}
function highlight(e) {
dropArea.classList.add('highlight')
}
function unhighlight(e) {
dropArea.classList.remove('highlight')
}
function handleDrop(e) {
let dt = e.dataTransfer
let files = dt.files
handleFiles(files)
}
function handleFiles(files) {
files = [...files]
initializeProgress(files.length)
files.forEach(uploadFile)
files.forEach(previewFile)
}
function uploadFile(file, i) {
var url = '/temp.php'
var xhr = new XMLHttpRequest()
var formData = new FormData(document.forms.myform)
xhr.open('POST', url, true)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
xhr.upload.addEventListener("progress", function(e) {
updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
})
xhr.addEventListener('readystatechange', function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
}
else if (xhr.readyState == 4 && xhr.status != 200) {
}
})
formData.append('file', file)
xhr.send(formData)
}
function previewFile(file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = function() {
let img = document.createElement('img')
img.src = reader.result
document.getElementById('gallery').appendChild(img)
}
}
let uploadProgress = []
let progressBar = document.getElementById('progress-bar')
function initializeProgress(numFiles) {
progressBar.value = 0
uploadProgress = []
for(let i = numFiles; i > 0; i--) {
uploadProgress.push(0)
}
}
function updateProgress(fileNumber, percent) {
uploadProgress[fileNumber] = percent
let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
console.debug('update', fileNumber, percent, total)
progressBar.value = total
}
And here's a html form like this with a php handler:
<div id="drop-area">
<form name="myform" class="my-form" enctype="multipart/form-data">
<div id="gallery"></div>
<p><input type="file" id="fileElem" name="Test[]" style="font-size: 15px;" multiple accept="image/*" onchange="handleFiles(this.files)"></p>
<label class="button" for="fileElem">Choose files</label>
<progress id="progress-bar" max=100 value=0></progress>
<div id="gallery"></div>
</form>
</div>
<?php
foreach ($_FILES['file']['error'] as $key => $error) {
if ($error = UPLOAD_ERROR_OK) {
$uploaddir = "/mnt/";
$uploaddir .= basename($_FILES['file']['name'][$key]);
if(file_exists(uploaddir)) {
unlink(uploaddir);
move_uploaded_file($_FILES['file']['tmp_name'][$key], $uploaddir);
}
else {
move_uploaded_file($_FILES['file']['tmp_name'][$key], $uploaddir);
}
}}
?>
Of course nothing works: files are not transferred to the folder. What am I doing wrong? Why are the files not being transferred?
Please help the young tudent.
I solved it myself, the error was in js:
formData.append('file[]', file);

Can't upload large files using XHR and FormData

I have created simple script using XMLHttpRequest. It sends text and (optionally) file. It works but problem is that large files (above 50MB) are not accepted. I thought that problem was with PHP's upload_max_filesize or post_max_size but it doesn't (I set it up 512MB). I don't know what to do now... Any ideas?
function publishPost() {
if (!event) { event = window.event; }
event.preventDefault();
var data = new FormData();
data.append('SelectedFile', document.querySelector('#post input').files[0]);
var x = new XMLHttpRequest();
x.open('POST', 'upload.php', true);
x.setRequestHeader('TEXT', post.innerHTML);
x.onload = function() {
if (x.readyState == XMLHttpRequest.DONE) {
if (x.responseText == '1') {
location.reload();
} else {
alert('Error: ' + x.responseText);
}
}
}
x.send(data);
}
And PHP:
$text = strip_tags($_SERVER['HTTP_TEXT']);
$file = $_FILES['SelectedFile']['name'];
$info = pathinfo($file);
$uniqid = uniqid();
if (!empty($file)) {
$newfile = '../files/'.$uniqid.'.'.$info['extension'];
if (move_uploaded_file($_FILES['SelectedFile']['tmp_name'], $newfile)) {
$file = $uniqid.'.'.$info['extension'];
}
}
// Adding to Database
My error is Undefined index: SelectedFile

Prevent refresh after ajax file upload with ASP Generic Handler

I am trying to upload a file to the server without refreshing page on completion. I currently managed to solve the upload part using XMLHttpRequest to the Generic Handler (.ashx). However I cannot find the solution to prevent it from refreshing, tried using event.preventDefault() and return false; on the ajax but it doesn't work.
The ajax script
$('#uploadFileButton').on('click', function (event) {
var counter;
function UploadFile() {
var files = $("#<%= file1.ClientID %>").get(0).files;
counter = 0;
// Loop through files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "FileUploadHandler.ashx");
ajax.send(formdata);
}
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress").html(Math.round(percent) + "% uploaded... please wait");
}
function completeHandler(event) {
counter++
$("#progress").html(counter + " " + event.target.responseText);
}
function errorHandler(event) {
$("#progress").html("Upload Failed");
} function abortHandler(event) {
$("#progress").html("Upload Aborted");
}
});
The FileUploadHandler.ashx
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile file = context.Request.Files[0];
string fname = context.Server.MapPath("~/Document/" + file.FileName);
file.SaveAs(fname);
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
And in case you need it, the index.aspx body
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="file1" runat="server" AllowMultiple="true"/>
<button id="uploadFileButton">Upload</button>
<div id="progress">
</div>
</form>
</body>
Anyone care to shed light on how to solve this?
GOT IT! Its actually the VS2017's "Enable Reload on Save" property is set to True which is the default. I followed the solution here , found it after googled "SaveAs refresh page". #RGS code IS RIGHT, its just my VS settings. Hope this helps others.
Use event.preventDetault() inside button click event. You have to call UploadFile() function inside button click event.
<script type="text/javascript">
$(document).ready(function (e) {
$('#uploadFileButton').click(function (event) {
var counter;
UploadFile();
event.preventDefault();
});
function UploadFile() {
var files = $("#<%= file1.ClientID %>").get(0).files;
counter = 0;
// Loop through files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "Handler.ashx");
ajax.send(formdata);
}
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress").html(Math.round(percent) + "% uploaded... please wait");
}
function completeHandler(event) {
counter++
$("#progress").html(counter + " " + event.target.responseText);
}
function errorHandler(event) {
$("#progress").html("Upload Failed");
}
function abortHandler(event) {
$("#progress").html("Upload Aborted");
}
});
</script>

How to get data from PHP in JSON and AJAX?

Hey guys I am fetching some data with PHP with is listing the folders and Inside the folders I have some images. But I am willing to know how can I get that data in JSON with AJAX to get the name of folders in a DropDown.
This is the code that I am using
JS
<html>
<head>
<script type="text/javascript">
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
list.innerHTML = req.responseText;
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}
</script>
</head>
<body onload="readDir('');">
<div id="subDir">
</div>
</body>
</html>
PHP
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
getList($dir);
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
print "<br/><a href='javascript:void' onClick='readDir(\"" . $path . "/" . basename($name) . "\")'><b>" . basename($name) . "</b></a>";
} else {
print "<br/><a><b>" . basename($name) . "</b></a>";
}
}
}
?>
Here you can see the code how is working: http://tdhdemo.com/phpfetch/
I'm not sure I get your question right but you can add your list to an array in PHP and display it using json_encode.
When receiving data from the ajax call, use JSON.parse to make it easily readable.
You can also separate files and folders if you want to use them in the future.
<?php
$dir = "./data/";
if (strlen($_GET['data']) > 0){$dir = $_GET['data'];}
echo json_encode(getList($dir));
function getList($name) {
$path = realpath($name);
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CATCH_GET_CHILD);
$folderContent = array("directories" => array(), "files" => array());
foreach($objects as $name => $object){
if (filetype($name) == "dir") {
array_push($folderContent["directories"], basename($name));
} else {
array_push($folderContent["files"], basename($name));
}
}
return $folderContent;
}
?>
Javascript :
function readDir(dirName) {
var req = getXmlHttp();
var list = document.getElementById('subDir');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.status == 200) {
contentList = JSON.parse(req.responseText);
for(i in contentList["directories"]){
list.innerHTML = list.innerHTML + contentList["directories"][i];
}
}
}
}
req.open('GET', 'getList.php?data=' + dirName, true);
req.send(null);
list.innerHTML = 'loading...';
}

Rename a uploaded file with AJAX

I'm trying to use the SitePoint Drag and Drop file upload to upload images to my site. My cshtml page contains the form and the userID for the current user. I would like to rename the file to the userID, but AJAX asynchronously uploads the image without sending the userID data along. Therefore I can't rename the file. How can I pass the userID from the cshtml page to the php page, via JS/AJAX, to be able to rename the file?
Here is the cshtml:
<form id="upload" action="test2.php" method="POST" enctype="multipart/form-data">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" accept="image" />
<input type="text" id="id" name="id" value="#userID" hidden /> //This is referencing a SQL query to get the UserID
//It's the data I want to pass along
<div id="filedrag">or drop files here</div>
<script src="filedrag.js"></script>
Here is the PHP:
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
$userID = ???
if ($fn) {
$file_ext = substr($fn, strripos($fn, '.'));
$newfilename = $userID.$file_ext;
// AJAX call
file_put_contents(
'uploads/' . $newfilename,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
Here is the full JS:
(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);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// 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";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();

Categories

Resources