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);
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 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();
};
I'm trying to POST a blob object from client written in angularJS to NodeJS server. I'm successfully receiving the message.
client side code is something like
var imgData = [/*about 8K of data read from file*/];
var blob = new Blob([imgData], { type: 'application/octet-binary'});
var reader = new FileReader();
reader.addEventListener("loadend", function() {
var request = new XMLHttpRequest();
request.open("POST", "https://xyzabc.io");
request.send(reader.result);
});
reader.readAsArrayBuffer(blob);
I have written a C++ addon as described in https://nodejs.org/api/addons.html
. when i'm trying to parse the arguments it detects attached data as v8::Object & not v8::arrayBuffer.
void RunCallback(const FunctionCallbackInfo<Value>& args) {
if (args[1]->Isobject()) {
//console.log('Not what i was expecting');
}
if (args[1]->IsArrayBuffer()) {
//console.log('this is what i'm looking for');
}
}
What am I doing wrong here?? I blob not supposed to be send that way??
I took client side code from https://developer.mozilla.org/en/docs/Web/API/Blob
In my module i'm did this like:
if (node::Buffer::HasInstance(args[1])) {
//this is buffer
}
And it's ok for node v4.
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