Can't create Base64 representation of binary JPEG - html

So, this must be something more than I have to struggle with. I let users store images, now privately, hence I need to be able to request images with the Authorization header. <img> doesn't allow this however (and no, I don't want to add a ?token=xxx to the request). So I have to load the image using axios.get and then convert the binary representation of the image to Base64, and embed the image using the Data URI. Simple, right?
So what I have to do is img.src=data:image/jpeg;base64,xxxxxxxxx where all the x:s should be replaced with the Base64 representation of the image. I tried using btoa but only got about 20 characters in my Base64. The image is on 700Kb.
Can it be that btoa can't handle images that size?
Are there any other way of doing this?
I do not use browserify or webpack, so I don't want to use Buffer to solve this.
EDIT: The first comment I received was actually the correct answer to my question, with just a small adjustment.
getBase64(arrayBuffer) {
var reader = new FileReader();
var that = this;
reader.onloadend = function () {
that.mainImage = reader.result;
};
reader.readAsDataURL(new Blob([new Uint8Array(arrayBuffer)], { type: 'image/jpeg' }));
}
I added a Blob to contain my ArrayBuffer, and I had to convert
ArrayBuffer to UInt8Array for the blob to be able to iterate over it.
And in my Vue template
<img class="responsive-img" :src="mainImage"></img>

try this.
getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
},
this.getBase64(this.selected_file);

Related

How to set value of an input with type of image file in HTML? [duplicate]

How can I set the value of this?
<input type="file" />
You cannot set it to a client side disk file system path, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
You can only set it to a publicly accessible web resource as seen in this answer, but this is clearly not the same as a client side disk file system path and it's therefore useless in that context.
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:
show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
the <input> tag to upload a new file
a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value
You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?
I have write full example for load URL to input file, and preview
you can check here
1
https://vulieumang.github.io/vuhocjs/file2input-input2file/
in short you can use this function
function loadURLToInputFiled(url){
getImgURL(url, (imgBlob)=>{
// Load img blob to input
// WIP: UTF8 character error
let fileName = 'hasFilename.jpg'
let file = new File([imgBlob], fileName,{type:"image/jpeg", lastModified:new Date().getTime()}, 'utf-8');
let container = new DataTransfer();
container.items.add(file);
document.querySelector('#file_input').files = container.files;
})
}
// xmlHTTP return blob respond
function getImgURL(url, callback){
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
As everyone else here has stated: You cannot upload just any file automatically with JavaScript.
HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.
What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...
function uploadFile (data) {
// define data and connections
var blob = new Blob([JSON.stringify(data)]);
var url = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myForm.php', true);
// define new form
var formData = new FormData();
formData.append('someUploadIdentifier', blob, 'someFileName.json');
// action after uploading happens
xhr.onload = function(e) {
console.log("File uploading completed!");
};
// do the uploading
console.log("File uploading started!");
xhr.send(formData);
}
// This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});
So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.
You need to create a DataTransfer and set the .files property of the input.
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);//your file(s) reference(s)
document.getElementById('input_field').files = dataTransfer.files;
the subject is very old but I think someone can need this answer!
<input type="file" />
<script>
// Get a reference to our file input
const fileInput = document.querySelector('input[type="file"]');
// Create a new File object
const myFile = new File(['Hello World!'], 'myFile.txt', {
type: 'text/plain',
lastModified: new Date(),
});
// Now let's create a DataTransfer to get a FileList
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);
fileInput.files = dataTransfer.files;
</script>
Define in html:
<input type="hidden" name="image" id="image"/>
In JS:
ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
.then(function (data) {
if (data.error){
...;
}
else {
$('#image').val(data.image);
}
})
After:
<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>
Actually we can do it.
we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form.
Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed.
So,
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FormToMultipartPostData postData =
new FormToMultipartPostData(webBrowser1, form);
postData.SetFile("fileField", #"C:\windows\win.ini");
postData.Submit();
}
Refer the below link for downloading and complete reference.
https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

Problem setting up multiple 3D models using a url as source with ar.js and A-frame

I'm just recently learning to code for A-frame projects. When trying to set up a scene with multiple targets in A-fram, the 3D model that was supposed to be displayed by one of them doesn´t appear. The model, like the marker, uses an URL as the original but only the latter works.
Separating the ar.js and A-frame proved that the problem was apparently on ar.js, however, I may be mistaken.
You can find my code in this link since it is giving me too much trouble to post here due to the URL in the code. The file's name is "Problem code":
https://github.com/BrandexGlobal/ARDuratex/tree/master
In HTML, you can use base64 data uris OR blobs for turning raw content into a viable url. This url should work in any place that any other url would work. I say should because I am not familiar with the framework that you are using (I'm anti-framework and pro-vanilla), so there is a slight chance that your framework might mess something up.
🢔 Because it appears as though you are new to Stackoverflow, I shall explain this checkmark here. After reading and reviewing my answer, if (and only if) you are thoroughly satisfied with the answer I have posted here, then you can reward me by clicking this checkmark to accept this answer as the best answer. If someone else posts a better answer, then click their checkmark. Clicking a checkmark is not permanent: if someone later on post a better answer, then you can click their checkmark and switch the best answer over to the new answer posted.
Example of plain ordinary image:
(function(mainImage) {
mainImage.title = mainImage.src;
})(document.getElementById("mainImage"));
<img src="https://i.stack.imgur.com/Lr5Kg.jpg" id="mainImage"/>
Example of using base64 data URI (notice how the url is the image itself). Also, see Jpillora's base64 encoder and this demo page.
(function(mainImage) {
mainImage.title = mainImage.src;
})(document.getElementById("mainImage"));
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgACADASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAABQYHCAT/xAAwEAABAwMBBQYFBQAAAAAAAAABAgMEBQYRAAcSEyExIkFRYYGRFSMyUpJCQ3Gxwf/EABcBAAMBAAAAAAAAAAAAAAAAAAEFBgT/xAAnEQABAwMCBQUBAAAAAAAAAAABAgMEAAURIcETFDFxgRJBUWGR0f/aAAwDAQACEQMRAD8Arm0G/Ztv1V6mUimImS0xEPArcCUpWtZAz/ATnHmNJlmVRFx14wbqjvVefwy86t5zeisjPIBv6MemlG5p7tQr1VkuOElya/knuCFlAHoEDQ6FVYASFxXHDNc+SXVIcAS31yMYBORjn46WQrhJekmO0jIJ8/vsM/VO7jaIzELmHVkEDxntkZ7ZqwXjCp9GgLdtxj4TUm+20uCCyhXiChHZPqDo7ZV5yJ7VNZrbYQ5Nb3o0lGNx0/accs94I5Hy6aiFz3/LQ1wGVr4RRub+/wCXjoxRZ7tI2OpqS3kuFK0TISRyLR4wXufmF9O7Ti+nkG2lA5JUAR85/lS1iDktxSVDQjSuDatCNr7QpbTzWKZU1mSyru7f1p/PPuNBZbLrMNC6dDjTkI/YcOCPMH/NaS2mWfHvK23IL7aS8k77Ln6m1eR1nCRaV32w8ph+lyZsYckLZQV8tTsuE407x2N9iDV3CuDMuPy75AIGNcYOOnUEZpQlRriuyayy5TRT22zucVbIZSBn3XqyxUpmzKTalLjrTGdIQsobwhLAOVnPTpn30t0eFX57m5FtyoIe6Bb4KAg+PMHVw2Z2tJocZ2TV18epSAAt1fUD7B4D+9BaJVzcb46AhtvoNdyc1icEW3BamletxXbbSv/Z" id="mainImage"/>
Example of using a Blob URI. Notice how the url is dynamically generated similar to a memory address pointer.
(function(){
var rawData = atob("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgACADASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAABQYHCAT/xAAwEAABAwMBBQYFBQAAAAAAAAABAgMEBQYRAAcSEyExIkFRYYGRFSMyUpJCQ3Gxwf/EABcBAAMBAAAAAAAAAAAAAAAAAAEFBgT/xAAnEQABAwMCBQUBAAAAAAAAAAABAgMEAAURIcETFDFxgRJBUWGR0f/aAAwDAQACEQMRAD8Arm0G/Ztv1V6mUimImS0xEPArcCUpWtZAz/ATnHmNJlmVRFx14wbqjvVefwy86t5zeisjPIBv6MemlG5p7tQr1VkuOElya/knuCFlAHoEDQ6FVYASFxXHDNc+SXVIcAS31yMYBORjn46WQrhJekmO0jIJ8/vsM/VO7jaIzELmHVkEDxntkZ7ZqwXjCp9GgLdtxj4TUm+20uCCyhXiChHZPqDo7ZV5yJ7VNZrbYQ5Nb3o0lGNx0/accs94I5Hy6aiFz3/LQ1wGVr4RRub+/wCXjoxRZ7tI2OpqS3kuFK0TISRyLR4wXufmF9O7Ti+nkG2lA5JUAR85/lS1iDktxSVDQjSuDatCNr7QpbTzWKZU1mSyru7f1p/PPuNBZbLrMNC6dDjTkI/YcOCPMH/NaS2mWfHvK23IL7aS8k77Ln6m1eR1nCRaV32w8ph+lyZsYckLZQV8tTsuE407x2N9iDV3CuDMuPy75AIGNcYOOnUEZpQlRriuyayy5TRT22zucVbIZSBn3XqyxUpmzKTalLjrTGdIQsobwhLAOVnPTpn30t0eFX57m5FtyoIe6Bb4KAg+PMHVw2Z2tJocZ2TV18epSAAt1fUD7B4D+9BaJVzcb46AhtvoNdyc1icEW3BamletxXbbSv/Z");
var rawDataLength = rawData.length;
var typedArrayView = new Uint8Array(rawDataLength);
for (var i=0; i<rawDataLength; i=i+1|0)
typedArrayView[i] = rawData.charCodeAt(i);
var img = document.body.appendChild(document.createElement("img"));
img.src = img.title = URL.createObjectURL(new Blob([
typedArrayView
], {type: "image/jpeg"}));
})();
Another example is that we can encode the image as a Base64 data URI, then use an XMLHttpRequest to HTTP-get the data URI's contents, but set the returnType property of the XMLHttpRequest to Blob so that we get a blob from the base64 data URI.
(function(){
var xhr = new XMLHttpRequest;
xhr.responseType = "blob";
xhr.open("GET", document.getElementById("base64DataURIImage").src);
xhr.onload = function(){
var img=document.body.appendChild(document.createElement("img"));
img.src = img.title = URL.createObjectURL(xhr.response);
}
xhr.send();
})();
(function(mainImage) {
mainImage.title = mainImage.src;
})(document.getElementById("base64DataURIImage"));
As a base64 URI: <img id="base64DataURIImage" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgACADASIAAhEBAxEB/8QAGAAAAwEBAAAAAAAAAAAAAAAABQYHCAT/xAAwEAABAwMBBQYFBQAAAAAAAAABAgMEBQYRAAcSEyExIkFRYYGRFSMyUpJCQ3Gxwf/EABcBAAMBAAAAAAAAAAAAAAAAAAEFBgT/xAAnEQABAwMCBQUBAAAAAAAAAAABAgMEAAURIcETFDFxgRJBUWGR0f/aAAwDAQACEQMRAD8Arm0G/Ztv1V6mUimImS0xEPArcCUpWtZAz/ATnHmNJlmVRFx14wbqjvVefwy86t5zeisjPIBv6MemlG5p7tQr1VkuOElya/knuCFlAHoEDQ6FVYASFxXHDNc+SXVIcAS31yMYBORjn46WQrhJekmO0jIJ8/vsM/VO7jaIzELmHVkEDxntkZ7ZqwXjCp9GgLdtxj4TUm+20uCCyhXiChHZPqDo7ZV5yJ7VNZrbYQ5Nb3o0lGNx0/accs94I5Hy6aiFz3/LQ1wGVr4RRub+/wCXjoxRZ7tI2OpqS3kuFK0TISRyLR4wXufmF9O7Ti+nkG2lA5JUAR85/lS1iDktxSVDQjSuDatCNr7QpbTzWKZU1mSyru7f1p/PPuNBZbLrMNC6dDjTkI/YcOCPMH/NaS2mWfHvK23IL7aS8k77Ln6m1eR1nCRaV32w8ph+lyZsYckLZQV8tTsuE407x2N9iDV3CuDMuPy75AIGNcYOOnUEZpQlRriuyayy5TRT22zucVbIZSBn3XqyxUpmzKTalLjrTGdIQsobwhLAOVnPTpn30t0eFX57m5FtyoIe6Bb4KAg+PMHVw2Z2tJocZ2TV18epSAAt1fUD7B4D+9BaJVzcb46AhtvoNdyc1icEW3BamletxXbbSv/Z" />
<br /><br />
Then turned into a blob:
Resources:
For base64 data URIs, see this MDN page
For my own library for correctly encoding base64 URIs with high unicode characters, see this Github repository
For blobs, see this MDN page

How to parse json newline delimited in Angular 2

I am writing an Angular 2 app (built with angular cli), and trying to use AWS Polly text-to-speech API.
According to the API you can request audio output as well as "Speech Marks" which can describe word timing, visemes, etc. The audio is delivered as "mp3" format, and the speech marks as "application/x-json-stream", which I understand as a "new line" delimited JSON. It cannot be parsed with JSON.parse() due to the new lines. I have yet been unable to read/parse this data. I have looked at several libs that are for "json streaming" but they are all built for node.js and won't work with Angular 2. My code is as follows...
onClick() {
AWS.config.region = 'us-west-2';
AWS.config.accessKeyId = 'xxxxx';
AWS.config.secretAccessKey = 'yyyyy';
let polly = new AWS.Polly();
var params = {
OutputFormat: 'json',
Text: 'Hello world',
VoiceId: 'Joanna',
SpeechMarkTypes:['viseme']
};
polly.synthesizeSpeech(params, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
var uInt8Array = new Uint8Array(data.AudioStream);
var arrayBuffer = uInt8Array.buffer;
var blob = new Blob([arrayBuffer]);
var url = URL.createObjectURL(blob);
this.audio.src = url;
this.audio.play(); // works fine
// speech marks info displays "application/x-json-stream"
console.log(data.ContentType);
}
});
Strangely enough Chrome browser knows how to read this data and displays it in the response.
Any help would be greatly appreciated.
I had the same problem. I saved the file so I could then read it line by line, accessing the JSON objects when I need to highlight words being read. Mind you this is probably not the most effective way, but an easy way to move on and get working on the fun stuff.
I am trying out different ways to work with Polly, will update answer if I find a better way
You can do it with:
https://www.npmjs.com/package/ndjson-parse
That worked for me.
But I can't play audio, I tried your code it says
DOMException: Failed to load because no supported source was found.

How write and immediately read a file nodeJS

I have to obtain a json that is incrusted inside a script tag in certain page... so I can't use regular scraping techniques, like cheerio.
Easy way out, write the file (download the page) to the server and then read it using string manipulation to extract the json (there are several) work on them and save to my db hapily.
the thing is that I'm too new to nodeJS, and can't get the code to work, I think that I'm trying to read the file before it is fully written, and if read it time before obtain [Object Object]...
Here's what I have so far...
var http = require('http');
var fs = require('fs');
var request = require('request');
var localFile = 'tmp/scraped_site_.html';
var url = "siteToBeScraped.com/?searchTerm=foobar"
// writing
var file = fs.createWriteStream(localFile);
var request = http.get(url, function(response) {
response.pipe(file);
});
//reading
var readedInfo = fs.readFileSync(localFile, function (err, content) {
callback(url, localFile);
console.log("READING: " + localFile);
console.log(err);
});
So first of all I think you should understand what went wrong.
The http request operation is asynchronous. This means that the callback code in http.get() will run sometime in the future, but the fs.readFileSync, due to its synchronous nature will execute and complete even before the http request will actually be sent to the background thread that will execute it, since they are both invoked in what is commonly known as the (same) tick. Also fs.readFileSync returns a value and does not use a callback.
Even if you replace fs.readFileSync with fs.readFile instead the code still might not work properly since the readFile operation might execute before the http response is fully read from the socket and written to the disk.
I strongly suggest reading: stackoverflow question and/or Understanding the node.js event loop
The correct place to invoke the file read is when the response stream has finished writing to the file, which would look something like this:
var request = http.get(url, function(response) {
response.pipe(file);
file.once('finish', function () {
fs.readFile(localFile, /* fill encoding here */, function(err, data) {
// do something with the data if there is no error
});
});
});
Of course this is a very raw and not recommended way to write asynchronous code but that is another discussion altogether.
Having said that, if you download a file, write it to the disk and then read it all back again to the memory for manipulation, you might as well forgo the file part and just read the response into a string right away. Your code will then look something like so (this can be implemented in several ways):
var request = http.get(url, function(response) {
var data = '';
function read() {
var chunk;
while ( chunk = response.read() ) {
data += chunk;
}
}
response.on('readable', read);
response.on('end', function () {
console.log('[%s]', data);
});
});
What you really should do IMO is to create a transform stream that will strip away all the data you need from the response, while not consuming too much memory and yielding this more elegantly looking code:
var request = http.get(url, function(response) {
response.pipe(yourTransformStream).pipe(file)
});
Implementing this transform stream, however, might prove slightly more complex. So if you're a node beginner and you don't plan on downloading big files or lots of small files than maybe loading the whole thing into memory and doing string manipulations on it might be simpler.
For further information about transformation streams:
node.js stream api
this wonderful guide by substack
this post from strongloop
Lastly, see if you can use any of the million node.js crawlers already out there :-) take a look at these search results on npm
According to the http module help 'get' does not return the response body
This is modified from the request example on the same page
What you need to do is process the response with in the callback (function) passed into http.request so it can be called when it is ready (async)
var http = require('http')
var fs = require('fs')
var localFile = 'tmp/scraped_site_.html'
var file = fs.createWriteStream(localFile)
var req = http.request('http://www.google.com.au', function(res) {
res.pipe(file)
res.on('end', function(){
file.end()
fs.readFile(localFile, function(err, buf){
console.log(buf.toString())
})
})
})
req.on('error', function(e) {
console.log('problem with request: ' + e.message)
})
req.end();
EDIT
I updated the example to read the file after it is created. This works by having a callback on the end event of the response which closes the pipe and then it can reopen the file for reading. Alternatively you can use
req.on('data', function(chunk){...})
to process the data as it arrives without putting it into a temporary file
My impression is that you serializing a js object into JSON by reading it from a stream that's downloading a file containing HTML. This is do-able yet hard. Its difficult to know when you're search expression is found because if you parse as the chunks come in then you never know if you received only context and you could never find what you're looking for because it was split into 2 or many parts which were never analyzed as a whole.
You could try something like this:
http.request('u/r/l',function(res){
res.on('data',function(data){
//parse data as it comes in
}
});
This allows you to read data as it comes in. You can handle it to save to disc, db, or even parse it if you accumulated the contents within the script tags into a single string then parsed objects in that.

phantomjs and passing imagedata as json

Can I use phantomjs to create an image of the contents of <div><iframe ..></div> (The div contains an iframe)
how do I make this image (binary data) as part of a json ? , as ({img: binary data}) ?
Is it possible to load the iframe by itself? If you can achieve that then there's no reason why you can't call var base64string = page.renderBase64(); to get a base-64 encoded string. See the API for renderBase64().
You can re-create the image later by evaluating img.src = "data:image/png;base64," + base64string;.