HTML 5 File API - Upload File to Server via JQuery - json

I have an ASP.NET MVC application. I'm trying to let the user upload files to the server. I need to use the HTML 5 File API. Currently, I have the following code:
<div><input id="filesToUpload" type="file" multiple="multiple" /></div>
<div><input type="button" value="upload" onclick="return uploadFiles();" /></div>
function uploadFiles() {
var files = null; // How do I get the files collection from "filesToUpload" here?
if ((files == null) || (files.length)) {
alert("Please choose at least one file to upload.");
return;
}
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.readAsBinaryString(f);
uploadFile(reader.result);
}
}
function uploadFile(f) {
// TODO: I'm not sure how to finish my actual AJAX request to post the file back to the server.
$.ajax({
url: "/uploadFile",
type: "PUT",
contentType: "application/json",
success: function (result) {
alert("File Uploaded!");
},
error: function (p1, p2, p3) {
alert("Upload Failed");
}
});
}
As you can see from the code, I have some knowledge gaps that I am trying to fill in.
How do I get the files collection from the "filesToUpload" HTML
element via JQuery? The reason I want this approach is because I do
not want to begin uploading until the user actually clicks the
"upload" button I've shown below.
What do I set as the "data" value in my $.ajax attempt?
What should the contentType be in my $.ajax attempt?
Thank you very much for your help!

Related

How to upload a file from pre-defined location in pc onto a webpage? without user intervension

I can have the user upload a file on a webpage using <input type='file' accept='text/plain' onchange='ReadTheTextfile(event)'>.
and then use javascript: FileReader,
reader.readAsText(event.target.files[0]); etc
but I already know that I want to read a file, which I already uploaded to the webserver.
How can I determine by myself which file I want to upload / read ? XMLHttpRequest ?
I don't want to read a file from the user's pc.
I want to read a file from the server, where my html files are also hosted.
You can retrive it via ajax call as follows.
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
Reference - https://stackoverflow.com/a/13329900/9640177

Using data in html from an API response

As a starter in html world, i would like to know and start using simple APIs to insert into my blog posts.
I tried to include as html values some simple API like: https://bitcoinfees.earn.com/api/v1/fees/recommended and I used examples given here: Display Json data in HTML table using javascript and some others more like: http://jsfiddle.net/sEwM6/258/
$.ajax({
url: '/echo/json/', //Change this path to your JSON file.
type: "post",
dataType: "json",
//Remove the "data" attribute, relevant to this example, but isn't necessary in deployment.
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
function drawTable(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(drawRow(data[i]));
}
$("#personDataTable").append(rows);
}
function drawRow(rowData) {
var row = $("<tr />")
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
return row;
}
but the result is always blank.
Please, can you give me some hint to can use that API and insert that numbers values for "fastestFee","halfHourFee","hourFee" as html values?
Thank you all!
Welcome to the html world. You are certainly right in assuming that data from APIs is a great way to make your websites more dynamic.
There is an example on W3 Schools on how to handle a http request. I think this is a good place to start https://www.w3schools.com/xml/xml_http.asp. You create a http object that does some sort of data fetching. In this example it is done with the xhttp.send(). At the same time you have a listener that monitors if the onreadystatechange property of the xhttp has changed. And if that change is status 200 (success) then perform some actions.
Here is my JSfiddle with example from your API
http://jsfiddle.net/zvqr6cxp/
Typically these actions would be to structure the returned data and then do something with the data, like show them in a table.
The example shows the native html xhttp object in use with an event listener. Typically as you learn more about this you would probably start using a framework such as jquery or Angular that can handle http requests smoother, keyword here is callback functions.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//In this example, I used your API link..first I would do is turn the JSON into a JS object
myObject = JSON.parse(xhttp.responseText)
document.getElementById("fast").innerHTML = myObject.fastestFee
document.getElementById("half").innerHTML = myObject.halfHourFee
document.getElementById("hour").innerHTML = myObject.hourFee
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();

How to use post from script?

Ths script generates a number:
function updateDue() {
var kmold1 = parseInt(<?php echo $km; ?>);
var kmnew1 = parseInt(document.getElementById("kminput").value);
var tot = kmnew1 - kmold1;
document.getElementById("kmtot").innerHTML = tot;
document.getElementById("kmnew").innerHTML = kmnew1;
document.getElementById("kmold").innerHTML = kmold;
}
The number is displayed on a webpage with this code:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
This is part of an form that is used to post to an other file.
How can I send the output of id="kmtot" to the next php file?
I have tried:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
Not working.
<input type="hidden" name="kmtot" id="kmtot">
If I add this, the number of id="kmtot" is not displayed on the webpage, and is not transfered.
Any hints or solutions?
If you are using jQuery, use this code:
$.ajax({
url: 'your-php-file.php',
method: 'post',
data: {
'kmtot': $('#kmtot').val(),
},
success: function(data) {
console.log(data);
}
})
In your-php-file.php, $_POST['kmtot'] will return the value of your element with the ID kmtot.
If you are not using jQuery, you could use Fetch API.

update jqPlot with json data (flicker)

So I've put this together from a bunch of examples around the internet. I'm pulling data from a text file and plotting it with jqPlot. I'm then recalling a function to continually update the plot from the file:
<div id="chart1" style="height:300px; width:500px;"></div>
<script class="code" type="text/javascript">
// Our ajax data renderer which here retrieves a text file.
// it could contact any source and pull data, however.
// The options argument isn't used in this renderer.
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "./jsondata.txt";
// passing in the url string as the jqPlot data argument is a handy
// shortcut for our renderer. You could also have used the
// "dataRendererOptions" option to pass in the url.
var plot1;
$(document).ready(function(){
plot1 = $.jqplot('chart1', jsonurl,{
title: "MY GRAPH",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
ConstantPlotter();
});
function ConstantPlotter() {
plot1.destroy();
plot1 = $.jqplot('chart1', jsonurl,{
title: "MY GRAPH",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
setTimeout(ConstantPlotter,100)
}
</script>
It works fine, but the plot flickers badly since it's being destroyed and recreated every time. The problem is that when I try to replace the 'destroy and plot' code with
plot1 = $.jqplot('chart1', jsonurl,{
title: "MY GRAPH",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
}).replot();
it works beautifully but I get a terrible memory leak.
Does anyone know a way to constantly update this plot from the file without having the terrible flicker? Thanks!

Uploading a file with a single button

All of the examples I've found so far to upload a file with PHP involve:
Choosing a file
Pressing a submit button to upload it (using post).
Here are a few:
Example 1 Example 2.
Is there a way to simply submit the file immediately after it's been chosen so the user doesn't have to click the "Upload" button? I know this is possible. Look at Dropbox's website, or Google Drive. I'm not sure if they use PHP, though.
You have 2 way :
user jquery :
<form id="frm" action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br/>
</form>
<script type="text/javascript">
<!--
$(document).ready(function(){
$('#file').change(function(){
$('#frm').submit();
});
})
-->
</script>
use flash uploader.
i hope help you...
HTML File upload buttons are not scriptable for security reasons.
What you want is the File API that is part of HTML5 http://www.w3.org/TR/FileAPI/ which contains capabilities to upload data via AJAX requests, etc.
unfortunately browser support is still spotty, so while you may be able to implement a drag and drop UI like Dropbox on Chrome or Firefox. You will need to have a fallback for IE.
http://www.html5rocks.com/en/features/file_access
Below code will solve your issue regardless of browser incompatibility. I use this very often.
function startUpload() {
var file_button = document.createElement('input');
file_button.type = "file";
file_button.id = "file_button1";
file_button.style.display = "none";
file_button.style.position = "absolute";
file_button.onchange = function() {
var form_data = new FormData();
var file = jQuery(this).get(0).files[0];
form_data.append('file', file);
form_data.append('type', type);
form_data.append('name', 'fileToUpload');
setTimeout(function() {
jQuery.ajax({
url: "/uploadfile.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: form_data,
xhr: function() {
var myXhr = jQuery.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', custom_progress, false);
}
return myXhr;
},
success: function(response) {
console.log(response);
}
});
}, 1000);
};
jQuery(document.body).append(file_button);
file_button.click();
jQuery("#file_button1").remove();
}
function custom_progress(e) {
if (e.lengthComputable) {
var x = (e.loaded / e.total) * 100;
jQuery("#progress").html(x + "%");
}
}
Your serverside code would look something like this
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
Found this solution here at Ajax file upload and progress