I have the following code:
function FileHandler() {
}
FileHandler.prototype.open = function(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
};
When I try to run it in the console, can I pass a local file as an argument where file is? What syntax would I use if I wanted to do that?
http://www.creativebloq.com/web-design/read-local-files-file-api-121518548
it shows exactly how you can do that:
The FileReader object allows us to read the content of a file once
we've got a file from the user. For security, the user must actively
give us the reference to the file in order for it to be readable.
There are a number of FileReader methods for getting a file's
contents
here is an example of how to use it: (code from the site)
var reader = new FileReader();
//create our FileReader object to read the file
reader.addEventListener("load", fileRead, false);
//add an event listener for the onloaded event
function fileRead(event){
//called when the load event fires on the FileReader
var pictureURL = event.target.result;
//the target of the event is the FileReader object instance
//the result property of the FileReader contains the file contents
}
reader.readAsDataURL(file);
//when the file is loaded, fileRead will be called
You can use an asynchronous function.
FileHandler.prototype.open = function(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState == 4) {
// The request is done; did it work?
if (rawFile.status == 200) {
// ***Yes, use `rawFile.responseText` here***
callback(rawFile.responseText);
} else {
// ***No, tell the callback the call failed***
callback(null);
}
};
rawFile.open("GET", file, false);
rawFile.send();
};
Related
Can you please tell me how can I correctly store some js file to localstorage and then run it.
So I have found some code that stores an image, but can I store a js file?
Here is the code:
https://gist.github.com/robnyman/1875344
// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
var rhinoStorage = localStorage.getItem("rhino"),
rhino = document.getElementById("rhino");
if (rhinoStorage) {
// Reuse existing Data URL from localStorage
rhino.setAttribute("src", rhinoStorage);
}
else {
// Create XHR and FileReader objects
var xhr = new XMLHttpRequest(),
fileReader = new FileReader();
xhr.open("GET", "rhino.png", true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
// onload needed since Google Chrome doesn't support addEventListener for FileReader
fileReader.onload = function (evt) {
// Read out file contents as a Data URL
var result = evt.target.result;
// Set image src to Data URL
rhino.setAttribute("src", result);
// Store Data URL in localStorage
try {
localStorage.setItem("rhino", result);
}
catch (e) {
console.log("Storage failed: " + e);
}
};
// Load blob as Data URL
fileReader.readAsDataURL(xhr.response);
}
}, false);
// Send XHR
xhr.send();
}
let MY_URL = "*"
let DataURL;
// basic JS way of getting the info from S3
let request = new XMLHttpRequest();
request.open('GET', MY_URL, true);
request.responseType = 'blob';
request.onload = function() {
var reader = new FileReader();
reader.readAsDataURL(request.response);
reader.onload = function(e){
DataURL = e.target.result;
};
};
request.send();
listenGetImageLoad(DataURL);
Here I am getting the Data URL of a file I am getting from the web. Next I want to Read it into a fileReader, but I keep getting the bug:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
My code for the fileReader is as follows::
const listenGetImageLoad = (DataURL) => {
const imageArray = Object.keys(images)
let async = imageArray.length
for (let image in images) {
const reader = new FileReader()
reader.addEventListener("load", () => {
const imageObject = new Image()
imageObject.addEventListener("load", (event) => {...})
reader.readAsDataURL(DataURL)
}
}
This function seems to be failing at reader.readAsDataURL(DataURL). I have no idea as to why this is the case. I am so sure that I have inputted a data URL into the FileReader function too.
You have two problems
You are calling listenGetImageLoad at the wrong time. XMLHttpRequest is async. So you need to call that inside your onload event.
Even when you correct the async issue you are passing the wrong thing to readAsDataURL(). It expects a blob or file object to be passed to it, not a string which is what a data url is.
Call listenGetImageLoad inside the load event passing in the response from the request to fix your issue.
request.onload = function() {
listenGetImageLoad(request.response);
};
Note you do not need to use readAsDataURL to show an image from a blob. Just call URL.createObjectURL() passing in the blob/file to get a url the browser will be able to load. Then set the src of the image with that url.
request.onload = function() {
var url = URL.createObjectURL(request.response);
yourImage.src = url;
};
I am following this and I want to upload any type of file to OneDrive. It says that it accepts a buffer for the file content but my following code does not seem to work in case of any type of file. The file gets uploaded but it cannot be opened so the contents are messed up for sure.
Using the following method I am trying to get the body contents so that I can send them with the request.
private fileToBuffer(file: File): Observable<any> {
return Observable.create(observer => {
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function () {
arrayBuffer = this.result;
observer.next(arrayBuffer);
observer.complete();
};
fileReader.readAsArrayBuffer(file);
});
}
I did not notice that the Angular 2's http's PUT was taking the body as string. So, I resorted to using XHR to upload a file with its contents.
var oReq = new XMLHttpRequest();
oReq.open("PUT", url, true);
oReq.setRequestHeader("Content-Type", "text/plain");
oReq.onload = function(e){
console.log('done');
};
oReq.send(arrayBuffer);
I am recording audio on my webpage using recorder.js which is creating a blob that represents a wav file. I want to send this blob file to my c# server code behind so that I can upload it to my azure storage. I've researched a lot on this and could only find results in sending the blob to php. So far, this is the only code I could find to send the blob to code behind:
function upload(blob) {
var xhr = new XMLHttpRequest();
xhr.open('POST', './addRecord.aspx', true);
xhr.onload = function (e) {
var result = e.target.result;
};
xhr.send(blob);
}
Then in my addRecord.aspx code behind Page_Load function I have:
Request.SaveAs(Server.MapPath("file.wav"), false);
When I check the file I saved, I cannot open it with anything. The file seems to be corrupted so I assume I wasn't able to pass the file successfully. I've also heard that this could be easy to do by using ajax but I'm not sure how to implement it. I'm open to any ideas on how to do this.
you can use this techniques:
Base-64
You can read the content from WAV file using FileReader API on javascript, and next coding the binary content to Base-64 to pass this like string chars.
The next is a simple example:
<input type="file" id="files" name="file" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process audio files.
if (!f.type.match('audio.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var xhr = new XMLHttpRequest();
xhr.open('POST', './addRecord.aspx/MyPostMethod', true);
xhr.onload = function (e) {
var result = e.target.result;
};
xhr.send('{"blob":"' + e.target.result + '"}');
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
The result is get like Base-64 encoded
I hope this help you
Hi guys!
I've got a little problem with my HTML5 XMLHttprequest uploader.
I read files with Filereader class from multiple file input, and after that upload one at the time as binary string. On the server I catch the bits on the input stream, put it in tmp file, etc. This part is good. The program terminated normally, send the response, and I see that in the header (eg with FireBug).
But with the JS, I catch only the last in the 'onreadystatechange'.
I don't see all response. Why? If somebody can solve this problem, it will be nice :)
You will see same jQuery and Template, don't worry :D
This is the JS:
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
var todo = {
progress:function(p){
$("div#up_curr_state").width(p+"%");
},
success:function(r,i){
$("#img"+i).attr("src",r);
$("div#upload_state").remove();
},
error:function(e){
alert("error:\n"+e);
}
};
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
var row = $('ul#image_list li').length;
row = row+i;
// Closure to capture the file information.
reader.onload = (function(theFile,s) {
return function(e) {
// Render thumbnail.
$("span#prod_img_nopic").hide();
$("div#prod_imgs").show();
var li = document.createElement('li');
li.className = "order_"+s+" active";
li.innerHTML = ['<img class="thumb" id="img'+s+'" src="', e.target.result,
'" title="', escape(theFile.name), '"/><div id="upload_state"><div id="up_curr_state"></div>Status</div>'].join('');
document.getElementById('image_list').insertBefore(li, null);
};
})(f,row);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
//upload the data
//#param object fileInputId input file id
//#param int fileIndex index of fileInputId
//#param string URL url for xhr event
//#param object todo functions of progress, success xhr, error xhr
//#param string method method of xhr event-def: 'POST'
var url = '{/literal}{$Conf.req_admin}{$SERVER_NAME}/{$ROOT_FILE}?mode={$_GET.mode}&action={$_GET.action}&addnew=product&imageupload={literal}'+f.type;
upload(f, row, url, todo);
}
the upload function:
function upload(file, fileIndex, Url, todo, method)
{
if (!method) {
var method = 'POST';
}
// take the file from the input
var reader = new FileReader();
reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
reader.onloadend = function(evt)
{
// create XHR instance
xhr = new XMLHttpRequest();
// send the file through POST
xhr.open(method, Url, true);
// make sure we have the sendAsBinary method on all browsers
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
this.send(blob);
}
// let's track upload progress
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
// get percentage of how much of the current file has been sent
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
// here you should write your own code how you wish to proces this
todo.progress(percentage);
});
// state change observer - we need to know when and if the file was successfully uploaded
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4)
{
// process success
resp=xhr.responseText;
todo.success(resp,fileIndex);
}else{
// process error
todo.error(resp);
}
};
// start sending
xhr.mySendAsBinary(evt.target.result);
};
}
}
}
and the starter event
document.getElementById('files').addEventListener('change', handleFileSelect, false);
It's a quite small mistake: You forgot to add a var statement:
// create XHR instance
var xhr = new XMLHttpRequest();
// ^^^ add this
With a readystatechange handler function like yours
function() {
if (xhr.status == 200 && xhr.readyState == 4) {
resp=xhr.responseText; // also a missing variable declaration, btw
todo.success(resp,fileIndex);
} else {
todo.error(resp);
}
}
only the latest xhr instance had been checked for their status and readyState when any request fired an event. Therefore, only when the last xhr triggers the event itself the success function would be executed.
Solution: Fix all your variable declarations, I guess this is not the only one (although affecting the behaviour heavily). You also might use this instead of xhr as a reference to the current XMLHttpRequest instance in the event handler.