I am testing uploading files with Ajax and PHP. The above code succeed without uploading the file why?
{
<form method="post" enctype="multipart/form-data">
<input id='files' type='file'>
</form>
<script>
document.getElementById('files').addEventListener('change', function (e) {
var file = this.files[0];
console.log(file);
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}
xhr.onreadystatechange = function (e) {
if (4 == this.readyState) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', 'arxeia', true);
xhr.send(file);
}, false);
</script>
</body>}
Do you thing that I should attach a post handler?
you should use FormData to send the file
document.getElementById('files').addEventListener('change', function (e) {
var file = this.files[0];
console.log(file);
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("file", file);
xhr.addEventListener('progress', function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}, false);
if (xhr.upload) {
xhr.upload.onprogress = function (e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
}
xhr.onreadystatechange = function (e) {
if (4 == this.readyState) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', 'arxeia', true);
xhr.send(fd);
}, false);
you will then be able to get the file on the server with $_FILES["file"]
Related
I have following function to convert local file to base64. When I run it, it writes the result (res) to console. How can I return the content of res from the function, so I can use it in another one?
function convertToBase64() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "1.jpg", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res);
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
(I am totally new in JavaScript.)
you can pass callback to your function to execute when file loaded
function convertToBase64(onLoad) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "1.jpg", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
var reader = new FileReader();
reader.onload = function(event) {
var res = event.target.result;
console.log(res);
onLoad(res); // callback
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
now you can do this :
convertToBase64(function(res) {
console.log('response loaded' , res);
});
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
I am using rtcmulticonnection.js. I want to save the video on server. Here are two files "index.html" and "save.php".
request.open("POST", url); does not post the data
here the source file link
"https://github.com/muaz-khan/RTCMultiConnection/blob/master/v2.2.2/demos/audio-video-screen-sharing-recording.html"
index.html
document.getElementById('recordAudioVideo').onclick = function() {
var localVideoStream = rmc.streams.selectFirst({
video: true,
local: true
});
if (!localVideoStream) return;
var recordingSession = {
audio: true,
video: true
};
var button = this;
if (button.innerHTML == 'Record Audio/Video') {
button.innerHTML = 'Stop Recording Audio/Video';
// http://www.rtcmulticonnection.org/docs/startRecording/
localVideoStream.startRecording(recordingSession);
} else if (button.innerHTML == 'Stop Recording Audio/Video') {
// http://www.rtcmulticonnection.org/docs/stopRecording/
localVideoStream.stopRecording(function(blob) {
//alert('Audio blob size in bytes: ' + blob.audio.size);
//alert('Video blob size in bytes: ' + blob.video.size);
var fileType = 'video'; // or "audio"
var fileName = 'ABCDEF.webm'; // or "wav"
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
console.log(formData);
xhr('save.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
callback(location.href + request.responseText);
}
};
request.open("POST", url);
request.send(data);
}
button.innerHTML = 'Record Audio/Video';
}, recordingSession);
}
save.php
<?php
// Muaz Khan - www.MuazKhan.com
// MIT License - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = './'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
the problem is at
request.open("POST", url);
request.send(data);
request.open("POST", url); does not post the data.it does not call url(means save.php).because i have alert some text to see if save.php is called or not. so it does not show any alertbox on client.how can i solve this problem.Also it shows no error on posting.
i need a JavaScript to download a group of images.
It should download some like this:
01.jpg
02.jpg
03.jpg....
but i get default file name:
5cEDZLQ.jpg
5Npv209.jpg
5FgtD69.jpg...
here my function to download:
function SaveToDisk(fileURL, fileName) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName;
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
window.webkitURL.revokeObjectURL(save.href);
}
tried various ways, but always download with the default name
Well is a long time but here is the solve.
Dowload the image/file using XMLHttpRequest and pass the result to the function saveAs from FileSaver.js
Example:
var xhr = new XMLHttpRequest();
var url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/272px-Google_2015_logo.svg.png';
var name = 'Google Logo.png';
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onprogress = function(e) {
if (e.lengthComputable) {
console.log( ((e.loaded / e.total) * 100) + '%');
}
};
xhr.onload = function() {
if (this.status === 200) {
var file = this.response;
saveAs(file, name);
console.log('File Saved!!!')
}
};
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
};
xhr.send();
How do I handle XMLHttpRequest data? I have a javascript/angular controller that takes some images and sends it to another page where I want to store the images to a database.
My code lokes like this:
modal.controller('UploadController', function ($scope) {
$scope.files = new Array();
$scope.getFiles = function (element){
$scope.$apply(function($scope){
for (var i = 0; i < element.files.length; i++) {
$scope.files.push(element.files[i])
}
console.log('files lenght : ' + $scope.files.length);
});
};
$scope.uploadFile = function () {
var data = new FormData();
var xhr = new XMLHttpRequest();
for(var i in $scope.files){
data.append("uploadedFile", $scope.files[i])
}
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "fileupload.html")
$scope.progressVisible = true
xhr.send(data);
}
function uploadProgress(evt) {
$scope.$apply(function(){
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
} else {
$scope.progress = 'unable to compute';
}
})
}
function uploadComplete(evt) {
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
};
function uploadCanceled(evt) {
$scope.$apply(function(){
scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
};
});
In the the response text from the alert I get to see the html code from fileupload.html.
How can I recieve the data in fileupload.html so I can store the images in a database?