Open file content using javascript - javascript

I have a object like this
{
id: "114898379136253"
leadgen_export_csv_url: "https://www.facebook.com/ads/lead_gen/export_csv/?id=379136253&type=form&source_type=graph_api",
locale: "en_US"
name: "Untitled form 11/7/2017"
status: "ACTIVE"
}
I want get the file content, to fill my database with the leads that come from this file.
In my case, I need to treat the CORS also, because is a external URL, but I need some help in this solution, transform in a buffer and read the buffer? Or exist some better solution ?
function loadFile(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file, true);
xhr.withCredentials = false;
xhr.responseType = 'blob';
xhr.onload = function (e) {
var reader = new FileReader();
reader.readAsDataURL(this.response);
reader.onload = function (e) {
console.log('DataURL:', e.target.result);
};
};
xhr.send();
}
The DataURL: in console log, return a Base64, and decoding the Base64 result, it returns me a webpage, but not the file.

Related

ReactJS Resize Base64

It works if you use the url https://i.imgur.com/6gMn1RD.png. However, when passing the string via axios, i have a network problem with the string being to large. To manage this... I want to resize the image to 100px/100px. I have been at this for 2 days and cannot find a solution anywhere.
So the steps should be as follows:
Get base64 string from url (see snippet below).
In the snippet below, before calling this.setState, convert the base64 to a smaller size of 100px/100px
Finally, we can call set state with the resized base64 string.
I have the following code snippet
convertAndSetAvatarUrlToBase64 = () => {
const url = this.state.avatarUrl;
const setAvatar = (base64) => {
// Resize base64 here
this.setState({ avatar: base64, fileAvatarImage: '' });
}
let getDataUri = function (url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
let reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
};
reader.readAsDataURL(xhr.response);
};
let proxyUrl = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyUrl + url);
xhr.responseType = 'blob';
xhr.send();
};
getDataUri(url, function (base64) {
setAvatar(base64);
})
}
Note: I've tried using the library resize-base64, but all I get is a DrawImage error relating to the canvas (something my friend said doesn't work well with react).

Blob image from database to Java and from Java to Javascript Image

I have Blob, which stored in db and i take it from database with java server like this:
Entity.java
#Column(name = "img")
private Blob img;
public Blob getImg() {
return img;
}
public void setImg(Blob img) {
this.img = img;
}
Repository.java
#Transactional
#Query(value = "SELECT img FROM articles WHERE category = ?", nativeQuery = true)
//Blob findP(String category);
Blob findPic(String category);
Controller.java
#RequestMapping(value="/Pic_test")
#ResponseBody
public Blob getPics() throws SQLException, IOException {
return remindRepository.findPic("Java");
}
Then I receive it with Javascript to image it:
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('http://localhost:8080/articles/Pic_test', function(dataUrl) {
var display = document.getElementById('display');
var url = window.URL.createObjectURL(new Blob([dataUrl]));
var img = new Image();
img.src = url;
document.getElementById("demo").innerHTML = img.src;
})
However, if I call my "img" Blob in java code, i have an error in server, but if I call it byte[], my picture is not shown just.
I can't comment the java part since I know nothing about it, but for the javascript one, what you do is... not correct.
You don't seem to understand what is a data URL, nor what you are doing here.
So a data URL is a string, made of an header and of some file content (data:|mime/type;|file-content).
A data URL is an URL that points to itself, useful to embed data that should normally be served from network.
Quite often, the file content part is encoded as base64, because the URI scheme is limited in its set of allowed characters, and that binary data couldn't be represented in this scheme.
Now let's see what you are doing here...
You are downloading a resource as a Blob. That's good, Blob are perfect objects to deal with binary data.
Then, you read this Blob a data URL. Less good, but I can see the logic, <img> can indeed load images from data URLs.
But then from this data URL string, you create a new Blob! This is completely wrong. The Blob you just created with new Blob([dataUrl]) is a text file, not your image file in any way. So yes, the data is still hidden somewhere in the base64 data which is itself in the data URL, but what your poor <img> will see when accessing the data hooked by the Blob URI is really just text, data:image/png;base64,iVBORw0... and not at all �PNG... like its parsing algo can read.
So the solution is quite easy: get rid of the FileReader step. You don't need it.
var xhr = new XMLHttpRequest();
xhr.open('get', 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
xhr.responseType = 'blob';
xhr.onload = display;
xhr.send();
function display(evt) {
// we did set xhr.responseType = "blob"
var blob = evt.target.response; // so this is a Blob
// hence, no need for anything else than
var url = URL.createObjectURL(blob);
var img = new Image();
img.src = url;
document.body.appendChild(img);
}
And if I may, all your thing could also just be
document.getElementById('display').src = 'http://localhost:8080/articles/Pic_test';

ionic 1 fileuri to blob not working

I am taking the image link as POST Method and I want to convert the image link as BLOB and store it on local storage for offline work.
function convertFileToDataURLviaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
I called the method as follows -
convertFileToDataURLviaFileReader($rootScope.currentUser.profile,function(base64Data){
window.localStorage.setItem(LOCAL_IMAGE_KEY, base64Data);
});
I am using this method but its not working. Would someone let me know the the problem and provide me solution for this?

how to instantiate new file object javascript

I'm having troubles instantiating a new file object in javascript.
Here's the general gist of what I'm trying to do. There is client side code that expecting a "file" type object. I need to access the file that's located on the server (game.smc), download it to the local machine and feed it to the client side code.
I did some research and found that creating a new blob object is the first step. But in the code below the blob object remains null and is never getting populated. Does the path in the xhr.open need to have the entire url? Maybe i'm missing an entire concept here not sure.
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/Roms/game.smc");
xhr.responseType = "blob";
xhr.onload = function()
{
blob = xhr.response;
}
xhr.send();
Once I can get the blob object populated I can then do this to convert it to a file object.
function blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
This is what I ended up doing. Shows how to get the blob object as well as convert it to a file type.
function autoLoadGame(fileName) {
var gameLocation = '/Content/Roms/Snes/' + fileName;
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", gameLocation, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
var blob = xhr.response;
var file = new File([blob], fileName, { type: '', lastModified: Date.now() });
snes_readfile(file);
}
}
xhr.responseType = "blob";
xhr.send();
}

Getting blob gives 404 error

could someone prompt me - how to save "blob in memory" to a file using Java Script?
e.g. I have in the page next blob-image:
<img src="blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630" class="g-img">
and I need to save this blob to a file (png/jpg).
The next code just gives:
GET blob:https%3A//drive.google.com/851b979c-92e9-4ef2-9152-8935f7793630 404 (Not Found)
so it seems, usual way to get the blobs doesn't work here.
Is there any workaround to save this blob-images from browser memory to a file, or, saying more exactly - to get them as a real blob using only "src" tag value?
Thank you.
var srcEl = evt.srcElement;
var CurI = document.getElementsByClassName('g-img');
[].forEach.call(CurI, function (el) {
var xhr = new XMLHttpRequest();
xhr.open('GET', el.src, true);
xhr.responseType = 'arraybuffer'; // xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(myBlob);
console.log(myBlob);
}
};
xhr.send();
console.log(el.src);
// saveAs(myBlob, 'my2image.png');
}
p.s. to use mediarecorder?

Categories

Resources