Javascript: FileUri to blob conversion - javascript

I want to upload files from local storage. But from local storage I'm getting file url something like file:///data/user/0/application_package/cache/IMG-199201092.jpg. I want to convert it to blob file or any array or object of file so that it can be send to server via XMLHttpRequest. So that on server i can save them.
I'ave tried this code:
var reader = new FileReader();
var blob_image = reader.readAsDataURL(imageUri);
but blob_image i couldn't fetch it on server via '$_FILES' as image or something.
I'm getting imageUri from
$cordovaImagePicker.getPictures(options)
.then(function (results)
{
for (var i = 0; i < results.length; i++)
{
var image_uri = results[i];
var fd = new FormData();
//Take the first selected file
var blobbb = new Blob([new Uint8Array(results[i])], { type: "file" });
fd.append("file", blobbb );
objXhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log( objXhr.responseText );
}
};
objXhr.open("POST", "http://someapi.com/api.php");
objXhr.send(fd);
}
}

Related

In REST API how to attach files to the body of form data in C#

I'm using Postman Rest API calls to upload file to Azure Blob. I want to understand how to attach files to the body of form data from frontend using C# code, so that it return me the result with some ID and File Type.
I think that this is a duplicated question
Adding the answer from the original post
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}

JavaScript - Send ArrayBuffer data to backend over websocket [guacamole]

I need to send data (a file) via websocket to my guacamole backend using the guacamole-common-js library.
The scenario is the following:
Drag and drop area is created
User puts a file in this area
File is read
A guac filestream is created and the file is sent to the guac backend
Steps 1 to 3 are already working, but I do not know, how to send the file to the guacamole backend.
That's my function when a file is dropped: (guac is a global var that initialized the Guacamole-Client function)
function drop(ev){
ev.preventDefault();
if (ev.dataTransfer.items) {
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
var reader = new FileReader();
reader.onloadend = function fileContentsLoaded (e){
const stream = guac.createFileStream(file.type, file.name);
const bytes = new Uint8Array(reader.result);
stream.sendBlob(bytes.buffer)
stream.sendEnd()
};
console.log(file)
reader.readAsArrayBuffer(file);
}
}
} else {
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
console.log(ev.dataTransfer.files[i].name);
}
}
}
The backend is also receiving the data and I am able to open the file on the remote server to which the file is sent by guacd, but the file does only contain kind of binary data.
Does someone already managed this or has an idea how I could send the data?
If you use Node.js in Backend, try handle it with Buffer.toString or Buffer.from.
I already found a solution...
The guacamole-common-js lib already provides a function for sending the buffer to the backend...
My "drop" functions looks now the following:
function drop(ev){
ev.preventDefault();
if (ev.dataTransfer.items) {
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
var reader = new FileReader();
reader.onloadend = function fileContentsLoaded (e){
const stream = guac.createFileStream(file.type, file.name);
var bufferWriter = new Guacamole.ArrayBufferWriter(stream)
bufferWriter.sendData(reader.result)
bufferWriter.sendEnd()
};
reader.readAsArrayBuffer(file);
}
}
} else {
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
console.log(ev.dataTransfer.files[i].name);
}
}
}

JS FileReader ArrayBuffer to Byte[] to pass contents of a file

I have a file upload area in my application, it allows uploads of images, .doc, .docx and pdf.
I need to pass the contents of the file in a byte[] to my api so that it can store the file.
I have tried to convert from ArrayBuffer to Uint8Array but i have not been successful.
Here is my code for reading the file and obtaiing the required information
Any help would be appreciated.
let myFile = ev.target.files[0];
if(myFile.size > 0){
let reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(myFile);
reader.onloadend = (ev) => {
var uintArray = new Uint8Array(reader.result.toString().length);
//var arrayBuffer = new ArrayBuffer(reader.result);
//var array = new Uint8Array(arrayBuffer);
let resourceModel = new AddForumThreadResourceRequestModel({
contentType: myFile.type,
fileName: myFile.name,
fileContent: uintArray
});
console.log(resourceModel);
this.forumApi.AddThreadResource(resourceModel).subscribe(
data => {
if(data != null || data == true){
this.errorCtrl.presentToast("New resource has been added to the thread");
}
});
}
Try to use argument of load event:
reader.onload = (e) => {
var uintArray = new Uint8Array(reader.result);
let resourceModel = new AddForumThreadResourceRequestModel({
contentType: myFile.type,
fileName: myFile.name,
fileContent: uintArray
});
console.log(resourceModel);
this.forumApi.AddThreadResource(resourceModel)
.subscribe( data => {
if(data != null || data == true){
this.errorCtrl.presentToast("New resource has been added to the thread");
}
});

URL encoding "data:image/jpg; base64" image

How can I encode the data:image/jpeg;base64 data url to be transmitted correctly through an AJAX POST. I have the following code xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true); that is doing so now.
However, the URL http://url-sent-to/image/data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…RRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/2Q==&imageid=testimagedata does not look like it will be correct, especially since it has = in it.
$(function () {
var fileInput = document.getElementById("file")
, renderButton = $("#renderButton")
, imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {"type":fileToBlob.type});
// do stuff with blob
console.log(blob);
// Find the selected file
if(event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function(file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if(e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if(e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});
// As soon as the user clicks the render button...
// Listen for "Render final image" click
renderButton.click(function (event) {
var dataUrl;
imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {
// `dataUrl` now contains a resized rendered image with
// a width of 300 pixels while keeping the ratio
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
}
var blob = dataURItoBlob(dataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
var saveImage = dataUrl;
//console.log(saveImage);
fd.append("myFile", blob);
xhr.open('POST', 'http://url-sent-to/image/' + saveImage + '&imageid=' + imageid.value, true);
xhr.send(fd);
I have a fiddle setup for an example of what I'm doing. Essentially, the user will select an image, enter a description, and hit render. When you check the Javascript console, you'll see a Blob is created, and the POST message at the bottom: http://jsfiddle.net/mattography/Lgduvce1/2/
You're looking for encodeURI(), which will do exactly what you're looking for.
Note that you're missing a ? to start your querystring.
Also note that making URLs that long is a bad idea; you should send a POST request instead.

Javascript arraybuffer to file in Django

people!
I have tried to send via HTTP POST (using AngularJS) the content of a file (images to be more precise) converted in ArrayBuffer (UInt8) to a Django server but I cannot manage to save it correctly in file on the server.
Javascript code:
filesToUpload = document.getElementById('files')
var files = filesToUpload.files;
for(var i = 0; i < files.length; i++)
{
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
var fileContent = e.target.result;
var bin = new Uint8Array(fileContent);
console.log(bin);
var request = $http({
url: urlAddImagesRestaurant,
method: "post",
data: {
fileStructure: fileToBeUploaded,
datafile: bin
}
});
return request.then( service.handleSuccess, service.handleError );
};
})(files[i]);
reader.readAsArrayBuffer(files[i]);
}
}
Has someone any idea how to save the content of the arraybuffer in django?

Categories

Resources