Send file to PHP server with JS - javascript

I can send files from the browser to the server using drag'n'drop and this code simply works fine:
var temp = new FormData();
temp.append("file_content",e.originalEvent.dataTransfer.files[0]);
//Ajax POST here...
Then I make a POST request (Ajax) to send that file to PHP and PHP can manipulate that file using $_FILES[file_content]. Easy.
My problem is that sometimes the user drops a folder and I already can manipulate the files inside that folder with JS in order to send them via Ajax. My problem is that PHP cant manipulate the $_FILE anymore, it is empty. My code:
var reader = entry.createReader();
reader.readEntries(function(entries) {
entries.forEach(function(dir,key) {
if (dir.isFile) {
var temp = new FormData();
temp.append("file_content",dir);
//Ajax POST here...
}
});
});
So I need someway to convert dir (which is of type FileEntry) to type File (e.originalEvent.dataTransfer.files[0]). How can I do this?

Related

Send recorded video using getUserMedia through form without using FormData

I have a form where users can record themselves with their webcam using getUserMedia, and I need to send the file they record to another page before saving the file to the server.
My question is how can I achieve this? So far I've generated a blob of the video, how do I send this through my form to the next page so I can access the file and then store it on the server?
Currently I'm generating the blob like so, which works:
let videoURL = window.URL.createObjectURL(blob, {autoRevoke: false});
But I'm not sure how I can send this file as part of the form's POST request without using AJAX and FormData. Is it even possible or am I approaching this incorrectly?
Create a file from your blob add it to a FileList and then overwrite the FileList of a file input in the form.
<form>
...
<input type="file" name="myvideo" id="fileinput">
...
</form>
var input = document.querySelector('#fileinput'); //the file input
var file = new File(blob, 'video_file.mp4'); // create new file
// Need to use a data transfer object to get a new FileList object
var datTran = new ClipboardEvent('').clipboardData || new DataTransfer();
datTran.items.add(file); // Add the file to the DT object
input.files = datTran.files; // overwrite the input file list with ours

Javascript - upload json and parse it

I'm building my web application using Javascript and Php, and currently want to implement such a feature, that allows user to upload (using
<input type="file" id="myFile" name="filename">
element) json file and then, by pressing some button next to it, to parse the data from this json into another json that will be saved on the server.
Which javascript features are recommended for doing this? Is it ok to go with ajax requests? Note that I don't want to upload that user's json anywhere on my server, I only want to use it as a user's input, which parsing result gets uploaded on the server.
Sure, you can read the file's content on browser side.
let file = document.getElementById('myFile').files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
let data = JSON.parse(reader.result);
...
};

How to create file object from server file using Javascript

I have one html which display data in table format by reading XLS file.This page giving two option to user. first is to ask user to upload xls file and second is to user already uploaded files by other users.
for first option (user upload file)
I am using JavaScript to fetch file data and convert it into html data.
beginFileHandling(e) {
let file = (e.target.files || e.dataTransfer.files)[0]
convertTodata(file) //this function has logic of reading file and convert it to data array for presentation in HTML
}
but for the second option (user can choose server files)
I need to have file object to make it work by upper method convertTodata(file). How can I achieve it using JavaScript or nodejs.
suppose I have file on server at following path 'docs/Test-files/employee.xls'
I am using xmlhttp to grab that file but how can I write it to JavaScript file object to use same method convertTodata(file).
var result = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'docs/Test-files/employee.xls', false);
xmlhttp.send();
if (xmlhttp.status == 200) {
result = xmlhttp.responseText;
}

AJAX Upload file straight after downloading it (without storing)

I'm making a JavaScript script that is going to essentially save an old game development sandbox website before the owners scrap it (and lose all of the games). I've created a script that downloads each game via AJAX, and would like to somehow upload it straight away, also using AJAX. How do I upload the downloaded file (that's stored in responseText, presumably) to a PHP page on another domain (that has cross origin headers enabled)?
I assume there must be a way of uploading the data from the first AJAX request, without transferring the responseText to another AJAX request (used to upload the file)? I've tried transferring the data, but as expected, it causes huge lag (and can crash the browser), as the files can be quite large.
Is there a way that an AJAX request can somehow upload individual packets as soon as they're recieved?
Thanks,
Dan.
You could use Firefox' moz-chunked-text and moz-chunked-arraybuffer response types. On the JavaScript side you can do something like this:
function downloadUpload() {
var downloadUrl = "server.com/largeFile.ext";
var uploadUrl = "receiver.net/upload.php";
var dataOffset = 0;
xhrDownload = new XMLHttpRequest();
xhrDownload.open("GET", downloadUrl, true);
xhrDownload.responseType = "moz-chunked-text"; // <- only works in Firefox
xhrDownload.onprogress = uploadData;
xhrDownload.send();
function uploadData() {
var data = {
file: downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1),
offset: dataOffset,
chunk: xhrDownload.responseText
};
xhrUpload = new XMLHttpRequest();
xhrUpload.open("POST", uploadUrl, true);
xhrUpload.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhrUpload.send(JSON.stringify(data));
dataOffset += xhrDownload.responseText.length;
};
}
On the PHP side you need something like this:
$in = fopen("php://input", "r");
$postContent = stream_get_contents($in);
fclose($in);
$o = json_decode($postContent);
file_put_contents($o->file . '-' . $o->offset . '.txt', $o->chunk);
These snippets will just give you the basic idea, you'll need to optimize the code yourself.

javascript read from a txt file and inject text into form

I apologize in the advance as I am a total beginner.
I have a pre-existing html form with text fields. I need to have a button that will allow me to upload a txt file (since when trying to look for answer about this, I learned javascript can't just access a file from my PC without me actively uploading it). Then I need the values from this txt file inserted into the text fields (for example, the form has: name, last name, phone etc - and the file will fill out this info).
I am going crazy trying to collect bits and pieces from other people's questions. any help would be greatly appreciated!
it depends on how you would like to have this handled, there are basically two options:
File Upload and page redirect
you could provide a file upload form to upload your textfile, redirect to the same page via form submission, handle the data on serverside (e.g. parse the file and get the values out of it) and let the server inject the values as default properties for the form file which is returned to the browser
XMLHttpRequest File Upload
in modern browsers, the native xhr object supports an upload property, so you could send the file via that upload property. it has to be sent to a serverside script that parses the file and returns the values in a fitting format, e.g. json (which would look like this: {'name':'somename', 'lastName':'someothername'}). then you have to register an eventlistener on completion of this upload (e.g. onload) and set these values on javascript side.
check this out for XMLHttpRequest upload (better solution in my opinion): https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
edit:
well, the easiest solution would be just to provide a textfield and paste the content of the file into this field, hit a button and the content is parsed. then you wouldn't rely on network traffic or even a serverside handling, but could do everything with javascript, e.g. like this:
dom:
<textarea id="tf"></textarea>
<button id="parse">fill form!</button>
js:
var tf = document.getElementById("tf");
document.getElementById("parse").addEventListener("click", function(){
var formData = JSON.parse(tf.value);
//if your textfile is in json format, the formData object now has all values
});
edit: from the link i posted in the comments:
<!-- The HTML -->
<input id="the-file" name="file" type="file">
<button id="sendfile">send</button>
and
document.getElementById('sendfile').addEventListener("click", function(){
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload/path', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var values = JSON.parse(xhr.responseText);
//these are your input elements you want to fill!
formNameInput.setAttribute('value', values.name);
formFirstNameInput.setAttribute('value', values.firstName);
}
}
xhr.send(formData);
});
as already said, your serverside has to parse the file and respond with json

Categories