Convert an image to base64 in javascript - javascript

I want to transform my image into base64 and then into JSON to send it via a post request to a server in java script.
I have looked for several solutions on the internet but none of them really work. Can someone explain to me the logic to have to achieve the code?
For now, I have this code:
JS code :
<script>
function convert (){
//image = btoa(URL="../static/images/images_final.jpg");
fetch("/predict" ,{
method: "POST",
body: JSON.stringify({result})
})
}
var file = window.document.querySelector('#form-base64-converter-encode-image-file').files[0];
getBase64(file);
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", e => {
const file = fileInput.files[0];
const reader = new FileReader();
reader.addEventListener("load", () => {
console.log(reader.result);
});
reader.readAsDataURL(file);
});
</script>
htlm code :
<form>
<input type="file" id="fileInput">
<button class="button"
type="reset"
onClick="convert()">
<h4>ENVOYER </h4>
</button>
</form>
API flask:
#app.post("/predict")
def predict_image():
req = request.get_json(force=True)
b64Image = req["image"]
buf = base64.b64decode(b64Image)
return print(b64Image[:20], buf[:20])

Related

Upload button unresponsive after first iteration JQUERY

I have a button that uploads the excel file.
<input type="file" id="input-excel" value="Choose File" accept=".xlsx" />
Below is an embedded script in the HTML to read the excel file and display it in the UI.
<script type="text/javascript">
// read and display the records from excel file on the screen
// passing in my button id here
$('#input-excel').change(function (e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function (e) {
var excelData = new Uint8Array(reader.result);
var wb = XLSX.read(excelData, { type: 'array' });
console.log(wb);
var htmlstr = XLSX.write(wb, {/* sheet: "Sheet1",*/ type: 'binary', bookType: 'html'});
$('#wrapper')[0].innerHTML += htmlstr;
};
});
</script>
#section scripts{
<script src="~/Scripts/ViewModels/RmaCreation/rmacreation.js"></script>
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script language="javascript" src="~/Scripts/xlsx.full.min.js"></script>
}
I am able to upload excel file in the first iteration. I can see the records from the excel file in the UI.
However, the button becomes unresponsive in the second iteration. How do I make this button responsive after every iteration?
https://jsfiddle.net/03ut9zjs/2/
<input type="file" id="input-excel" value="Choose File" accept=".xlsx" />
<div id="wrapper">
</div>
// read and display the records from excel file on the screen
// passing in my button id here
$('#input-excel').change(function (e) {
$('#wrapper')[0].innerHTML ="";
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function (e) {
var excelData = new Uint8Array(reader.result);
var wb = XLSX.read(excelData, { type: 'array' });
console.log(wb);
var htmlstr = XLSX.write(wb, {/* sheet: "Sheet1",*/ type: 'binary', bookType: 'html'});
$('#wrapper')[0].innerHTML += htmlstr;
};
});
You haven't included wrapper div in your code so i am not sure where/how you've placed it.
It seems to work fine in this fiddle. Are you able to recreate the issue here?

Getting image from a input field with Javascript to parse it to an API?

Currently trying to make use of an image upload class I created in php that saves an image to a folder and a text file but I want to save it from an api that I call in Javascript instead of by submitting a form.
Here I am trying to call the api
async function createTweet(e) {
const id = document.getElementById('user-id').getAttribute('data-user-id');
const tweet = e.target.parentNode.parentNode.querySelectorAll('input')[1]
.value;
const image = e.target.parentNode.parentNode.querySelectorAll('input')[0];
console.log(image);
const data = new FormData();
data.append('userId', id);
data.append('tweet', tweet);
data.append('tweet-image', image);
try {
const conn = await fetch('php/api/api-create-tweet.php', {
method: 'POST',
body: data,
});
const res = await conn.text();
getData();
// TODO show user he has created a tweet
} catch (error) {
console.log(error);
}
}
Just wondering what I can do with the image so I can read the file in my api with $_FILES['tweet-image'] and if I need to do anything to the form data to make it form type enctype
The code should work with some changes. You have two ways of doing it (see FormData # developer.mozilla.org):
Let's say you have a simple form:
<!-- just an example -->
<form method="post" action="form.php" enctype="multipart/form-data">
<input type="text" name="tweet" />
<input type="file" name="image" />
<input type="submit" />
</form>
<script>
/* prevent sending the form */
var form = document.forms[0];
form.onsubmit = function(e) {
e.preventDefault();
sendForm();
}
</script>
A. importing the <form> directly into FormData():
<script>
async function sendForm() {
// import form input here ->
const data = new FormData(form);
const conn = await fetch('form.php', {
method: 'POST',
body: data
});
const res = await conn.text();
}
</script>
B. make sure you actually append the .files[0] from the input[type="file"] into the formData():
<script>
async function sendForm() {
const data = new FormData();
const tweet = form["tweet"].value;
// notice the use of .files[0] -->
const image = form["image"].files[0];
data.append("tweet", tweet);
data.append("image", image);
const conn = await fetch('form.php', {
method: 'POST',
body: data
});
const res = await conn.text();
}
</script>
Then in your PHP file you should be able to access both $_POST["tweet"] (text) and $_FILES["image"] (file) in this example.

Upload image in angular js

I want to upload the image in angular js the image name need to send to db and the uploaded image move to an folder(target location) Same like move_uploaded_file in PHP. I have implemented as below:
<input type="file" id="file" name="file" ng-model="machineimage"/>
<button ng-click="uploadMachineImage($index)">Add</button>
In controller:
$scope.uploadMachineImage = function() {
var imgobject = document.getElementById('file').files[0];
console.log(imgobject['name']);
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
console.log(data);
}
r.readAsBinaryString(imgobject);
};

How can I use filereader to parse csv file and convert it into an array?

I have this in my html page:
<input type="file" id="fileInput" />
and this in my javascript page:
window.onload = function () {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function (e) {
// code that handles reading the text file
var file = fileInput.files[0];
var textType = /text.*/;
// checks if the file is a text file
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
I want to be able to convert the Filereader into an array so I can do something like:
document.getElementById("today").innerHTML = today[0];
Is this possible? I also don't think this is the way to read a csv file using filereader.
UPDATE: I have figured out how to get the csv file and turn it into an array by the following code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function (data) { processData(data); }
});
function processData(csv) {
var temp = new Array();
temp = csv.split(",");
document.getElementById("today").innerHTML = temp[0];
}
});
Now I am wondering if there is a way to use FileReader() so I can select the file from the html page instead of using url: "data.csv" so I can select multiple files.
You can handle this a few ways. You might think to ajax the file to a PHP script, then do something like $csvData[] = fgetcsv($file). Then you can echo json_encode($csvData);. It may be an extra http/server request but processing files is much easier.
There are some Javascript libraries that you wouldn't need to run server-side scripts for - JQuery CSV and PapaParse

Trouble uploading binary files using JavaScript FileReader API

New to javascript, having trouble figuring this out, help!
I am trying to use the Javascript FileReader API to read files to upload to a server. So far, it works great for text files.
When I try to upload binary files, such as image/.doc, the files seem to be corrupted, and do not open.
Using dojo on the client side, and java on the server side, with dwr to handle remote method calls. Code :
Using a html file input, so a user can select multiple files to upload at once :
<input type="file" id="fileInput" multiple>
And the javascript code which reads the file content:
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
// fileContent object contains the content of the read file
};
})(this.filesToBeUploaded[i]);
reader.readAsBinaryString(this.filesToBeUploaded[i]);
}
}
The fileContent object will be sent as a parameter to a java method, which will write the file.
public boolean uploadFile(String fileName, String fileContent) {
try {
File file = new File("/home/user/files/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
logger.error("Error uploading files: ", ex);
return false;
} catch (IOException ioe) {
logger.error("Error uploading files: ", ioe);
return false;
}
return true;
}
I have read some answers suggesting the use of xhr and servlets to achieve this.
Is there a way to use FileReader, so that it can read files of any type (text, image, excel etc.) ?
I have tried using reader.readAsBinaryString() and reader.readAsDataUrl() (Decoded the base64 fileContent before writing to a file), but they did not seem to work.
PS :
1. Also tried reader.readAsArrayBuffer(), the resultant ArrayBuffer object shows some byteLength, but no content, and when this is passed to the server, all I see is {}.
This bit of code is intended to work on only newer versions of browsers..
Thanks N.M! So, it looks like ArrayBuffer objects cannot be used directly, and a DataView must be created in order to use them. Below is what worked -
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
var int8View = new Int8Array(fileContent);
// now int8View object has the content of the read file!
};
})(this.filesToBeUploaded[i]);
reader.readAsArrayBuffer(this.filesToBeUploaded[i]);
}
}
Refer N.M 's comments to the question for links to the relevant pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
//here ajax
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>

Categories

Resources