Upload base64 image to .NET webservice and convert it there - javascript

I have a function that sends data through data:JSON.stringify(formdata)using POST to a remove .NET webservice. I have no problem this far. What I want to do it to add also add a another value to the formdata JSON that will hold a base64 image data and send it to the server, and there I will convert it back to a JPEG image.
How can I so that? I already have a preview function that created a preview, but also create a base64 image:
function previewFile() {
var preview = document.querySelector('.uploadimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
I see many question people asking how to upload image to the server. I want to stay with the current configuration but just pass the base64 image data to the server as a string. I see many developers struggling with that, and most of them just engine up creating a form in javascript and submitting like that.

Here is a recent way I did this:
string base64 = base64string.Substring(base64string.IndexOf(',') + 1);
byte[] imageData = Convert.FromBase64String(base64);
Image img;
using (var ms = new MemoryStream(imageData, 0, imageData.Length)) {
img = Image.FromStream(ms, true);
You will need:
using System.Drawing;
OR to simply convert to a jpg, use this:
File.WriteAllBytes("image.jpeg", Convert.FromBase64String(base64));
For sending the data I use the following JS:
function sendImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function (e) {
$("#imgImage").attr("src", e.target.result); //show a preview
//send e.target.result as a string to your webservice
};
FR.readAsDataURL(this.files[0]);
}
}
I use this event to listen for uploaded files:
document.getElementById("fileid").addEventListener("change", sendImage, false);
And the front end:
<input type="file" id="fileid" />

Related

Creating new blob from older one that is stored in local storage

I have basic html page where I want to upload image file, and after closing or reloading page I want that image to be there.
HTML code is :
<input type='file' accept="image/*">
<img alt="your image" height=400 width=auto>
Javascript code:
let img = document.querySelector('img');
document.body.onload = () => {
if(localStorage.image){
let source = JSON.parse(localStorage.image)
let file = new File([source], 'download.jpg', {type: 'image/jpeg', lastModified: Date.now()})
img.src = URL.createObjectURL(file)
}
}
document.querySelector('input[type="file"]').addEventListener('change', function() {
img.src = URL.createObjectURL(this.files[0])
localStorage.image = JSON.stringify(img.src)
});
My questions are:
When I console.log(localStorage.image), after uploading and reloading page, I will get one blob, and because from security reasons I can't use same blob, I tried to make new File and then from that file to create blob that I can later use, but when I console.log new blob (conosle.log(img.src)) I received different blob, so my question is why that happened, is there a way to correct that, I see that these two files has different file.size but when I want to change that it stays same
Also is there a second way to do that
As you can't persist blob objects between sessions (the blob URL will expire), you need to use a serializable format such as a data URL. Using a FileReader you can read the image file straight to a data url, and this can be stored in localStorage.
const fileReader = new FileReader();
fileReader.addEventListener('loadend', function() {
img.src = fileReader.result;
storage['image'] = fileReader.result;
})
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files.length > 0) {
fileReader.readAsDataURL(this.files[0]);
}
});
Here is a pen where I modified your code to use FileReader and data URLs (had to use sessionStorage because of codepen but localStorage should work)
https://codepen.io/Douile/pen/gOwORea?editors=1011

Extract data from uploaded file without submittng the file in JavaScript?

I want to take a user uploaded a file in Javascript and extract data from it without submitting the page and process that data for giving other options in the form on the same page.
It would be of great help if anyone could please help me out here.
Use the HTML 5 file API and FileReader, it allows you to work with files directly on the browser.
Here's a full example:
<input type="file" id="input" onchange="handleFiles(this.files)">
<div id="output">
</div>
<script type="text/javascript">
function handleFiles(files) {
//$("#output").html("got: "+files[0].name);
var reader = new FileReader();
reader.onload = function(e) {
$("#output").html(reader.result);
}
reader.readAsText(files[0]);
}
</script>
Please read this: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
and read this:
https://www.w3.org/TR/FileAPI/#APIASynch
The FileReader class provides the following useful methods:
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
....
Please read the above links, they will provide all the examples for you.
Here is the example of how to access a file's content.
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
// Do everything what you need with the file's content(e.target.result)
console.log(e.target.result);
};
})(f);
reader.readAsText(f);
}
document
.getElementById("upload")
.addEventListener("change", handleFileSelect, false);

How to get the file object on success callback of cordova camera?

Currently I am using the following approach where it is giving details of file but not the actual object it seems like one we get from in javascript/jQuery. Does any one having the clue how to get the file object from File URI /native URI from mobile ios/android filesystem using cordova and javascript?
Below is the snippet I am using currently..
window.resolveLocalFileSystemURL(
filepath,
function(fileEntry) {
fileEntry.file(
function(file) {
var reader = new FileReader();
reader.onloadend = function() {
var imgBlob = new Blob([this.result], {type: "image/jpeg"});
var uploadedFile = imgBlob;
uploadedFile.name = file.name;
alert("Importing Asset from Camera.. " + uploadedFile.name);
alert(uploadedFile.type);
alert(uploadedFile.size);
importAsset(uploadedFile);
};
reader.readAsArrayBuffer(file);
},
function(error) { alert("Error in fileEntry.file():" + error) })
},
function(error) { alert("Error in window.resolveLocalFileSystemURL():" + error) }
);
Note: FileTransfer.upload() will not work in my case.
Above snippet I am using after taking from Append image file to form data - Cordova/Angular after going through the existing Q&A from #SO
Base64 Image Upload will work both in iOS/Android as I have tried:
As for iOS There is only one way to show image is using base64 format.You can use cordova-camera-plugin to to generate base64 image and put on img tag of HTML.I have set the flag to get data in jpeg,base64 in camera plugin.
<img id="cardImg">
Store the base64 image in javascript variable as:
var imgdata=data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
Then Simply pass data to img tag of HTML as:
cardImg.src=imgdata;
Done!

javascript Howto decode file saved as base64 string and download it

how must I decode base64 string and download file from base64 string?
Previosly, I encoded a file with:
var strEncoded="";
file = $('#fileinput1')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
strEncoded = reader.result;
};
Thank you
You can create a <a> link and give the data to its href. For example i used a data/image base64 like this:
<a href="data:image/png;base64,iVBORw0K........" download>Download</a>
download attribute would do the work.
Or simply try this:
location.href = strEncoded;
And in a function:
download(dataUrl) {
location.href = dataUrl;
}
Download
Don't use the b64 version, but instead go directly with the File object you've got from your input.
Up to date browsers do support anchor's download attribute, then you just have to do a.href = URL.createObjectURL(yourFile); a.download = 'yourfile.whateverExtension'.
For older browsers, there are a few hacks, all condensed in the great FileSaver.js library.
Then all you need to do is
var inp = document.querySelector('input');
inp.onchange = function(){
saveAs(this.files[0], 'yourFile.extension');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.js"></script>
<input type="file"/>

Using FileReader() to read an image from HTML form

I am trying to use the readAsDataURL function for a javascript FileReader in order to retrieve data from an html form to upload it into a database. I currently have a file Object from the form but cannot get it into a form to put into a database.
HTML
input type="file" style="width: 300px" id="costumePicUpload" multiple
button type="submit" onclick="submitForm()">SUBMIT</button
JavaScript
function submitForm(){
var file = document.getElementById("costumePicUpload").files[0];
var reader = new FileReader();
var img;
reader.onloadend = function(e) {
img = new Image();
img.src = e.target.result;
if(e.target.error){
alert(e.target.error.code);
}
};
reader.readAsDataURL(file);
};
}
When I output the link in an alert it just says undefined. Does anyone know how I can fix this?
UPDATE
I was able to get a FileError.NOT_READABLE_ERR but have no idea what could be causing this.
I faced the same problem here is code
Html code
<input type="file" name="costumePicUpload" id="costumePicUpload" onChange="viewImage(this)" >
<img src="#" id="imageThumb">
Javascript Function
function viewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageThumb').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
When we choose the image file to upload it will read image using file reader and set it as a source for another image with id "imageThumb".

Categories