Javascript arraybuffer to file in Django - javascript

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?

Related

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);
}
}
}

Javascript: FileUri to blob conversion

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);
}
}

Reduce size of image when converted to Base64

I am using the File reader in JavaScript,i need to Post my image to WebApi and convert it into byte Array and save it in server,Its working fine,Now my problem is base64 string increasing the size of image, Let say if i upload image of 30Kb, it is storing has 389Kb in server,How i can save in same size or reduce size of image need help
//File Reader
function OnFileEditImageEntry(file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
var ImageBase64 = evt.target.result;
return ImageBase64 ;
};
reader.readAsDataURL(file);
}
//WEB API//
public IHttpActionResult UpdateUserDetails(ImageModel model)
{
try
{
if (model.ImageBase64 != "")
{
var PicDataUrl = "";
string ftpurl = "ftp://xxx.xxxxx.xxxx/";
var username = "xxx";
var password = "xxxxx";
string UploadDirectory = "xxxx/xx";
string FileName =model.ImageFileName;
String uploadUrl = String.Format("{0}{1}/{2}", ftpurl, UploadDirectory,FileName);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential(username, password);
req.EnableSsl = false;
req.UseBinary = true;
req.UsePassive = true;
byte[] data =Convert.FromBase64String(model.ImageBase64);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
}
}
}
Send the raw binary instead of increasing the size ~30% with base64/FileReader
with fetch
// sends the raw binary
fetch('http://example.com/upload', {method: 'post', body: file})
// Append the blob/file to a FormData and send it
var fd = new FormData()
fd.append('file', file, file.name)
fetch('http://example.com/upload', {method: 'post', body: fd})
With XHR
// xhr = new ...
// xhr.open(...)
xhr.send(file) // or
xhr.send(fd) // send the FormData
Normally when uploading files, try to avoid sending a json as many developers tends to to wrong. Binary data in json is equal to bad practice (and larger size) eg:
$.post(url, {
name: '',
data: base64
})
Use the FormData#append as much as possible or if you feel like it:
fd.append('json', json)

JSONifying a Blob file

I am trying to JSONify a blob file so that I can send it over AJAX requests. I have tried with the code below without any success. When I parse a JSONified file, I only get a different file with much smaller size.
function test(blob, cb) {
var fileReader = new FileReader()
fileReader.readAsArrayBuffer(blob)
fileReader.onloadend = function() {
// client
var arry = Array.from(new Uint8Array(fileReader.result))
var data = {data: arry }
var json = JSON.stringify(data)
// server
var parse = JSON.parse(json)
var arr = parse.data.buffer
var blob = new Blob([arr])
}
}
You can try to use FileReader.readAsDataURL() method, and send the data as base64 encoded string, and than decode it on the server side. Base64 string will be much smaller than json string representing an array.
Here is an example
function getBase64() {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
document.getElementById("result").value = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="getBase64()" />
<br/>
<textarea id="result"></textarea>
You can use FormData.
JQuery example (for simplicity):
var oFormData = new FormData();
$(':input', this).each(function (){
if(this.name){
var oValue = this.value;
if(this.type == 'file'){
oValue = this.files[0]; //TODO if "input file multiple" need loop each value
}
oFormData.append(this.name, oValue);
}
});
$.ajax({
url: 'http://example.com/xhr',
type: "POST",
data: oFormData,
processData: false,
contentType: false,
error: function (oRequest, sTextStatus, oErrorThrown){
console.log(sTextStatus);
},
success: function (oData, sTextStatus, oRequest){
console.log(oData);
},
});

How to print or save the online edited image (with javascript/jQuery)?

I made an simple image manipulation experiment with html, css and javascript/jquery.
We can upload an image from local drive and displayed in browser.
After that we can also edit/tag the displayed image.
I use this jquery image tag plugin.
Then I think about, how can i save/print the edited image?
This is my code snippet :
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
$('#myImg').imageTag();
};
Here's the real live app : http://nanonimos.com/upload-tag-image/
and this is the source code.
Any clue/advice would be greatly appreciated :)
You can convert the whole div to an canvas then convert the canvas into data uri(png,jpeg).
Check this Fiddlecanvastoimage for more.
Use this function(From Stackoverflow) to convert dataURI to blob:
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
and then whenever you want to save just post this file to server.
In HTML5 you can do like this:
var blob = dataURItoBlob(data);
var fd = new FormData();
fd.append("imageFile", blob);
Then send it with ajax like this:
$.ajax({
type: "POST",
url:"url to file",
data: fd,
success: function(result){
//check success
};
});

Categories

Resources