image to base64 in javascript and c# (frontend and backend) is different - javascript

I am trying to convert an image to base64 to upload it on sharepoint site but it is throwing 400:bad request error. when i checked properly then i found out that the base64 i am sending is endcoded by javascript and it is different than what is expected by sharepoint. I have attached 2 images here describing the difference. Can anyone help me to get the proper encoded data using javascript ?
javascript encoded base64
c# encoded base64
var files = $("#myfile").get(0).files;
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
console.log(reader.result);
}

Could try : reader.result.split("base64,")[1]
Removes the "base64," start of the string.

Please try this , i am using this in my project , its working for me
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
}
"thePictureDataAsString " variable got Base64 string
.........................................................................
i am getting file like this in my project
public ActionResult SaveMake(string inputMakeName, HttpPostedFileBase file)
{
MakeModel objMakeModel = new MakeModel();
if (file.ContentType.Contains("image"))
{
string theFileName = Path.GetFileName(file.FileName);
byte[] thePictureAsBytes = new byte[file.ContentLength];
using (BinaryReader theReader = new BinaryReader(file.InputStream))
{
thePictureAsBytes = theReader.ReadBytes(file.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);
objMakeModel.ImageBase64 = thePictureDataAsString;
objMakeModel.Make1 = inputMakeName;
}
string response = _apiHelper.ConvertIntoReturnStringPostRequest<MakeModel>(objMakeModel, "api/Transaction/SaveMakes/");
// string response = _apiHelper.SaveMake(objMakeModel, "api/Transaction/SaveMakes/");
return RedirectToAction("AddVehicleMaintenance");
}

Related

Convert input files to byte[] javascript

I'm working on a REST web application that manages documents between users and uploaders. The backend is written in Java and my Document entity contains, besides various attributes, a byte[] content. I was able to send a file created at server side by
#GET
...
document.setContent(Files.readAllBytes(Paths.get("WEB-INF/testFile.txt")));
return Response.ok(document).build();
and retrieve it at front-end (vueJs) through
async function download(file) {
const fileURL = window.URL.createObjectURL(new Blob([atob(file.content)]));
const fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download",`${file.name}.${file.type}`);
document.body.appendChild(fileLink);
fileLink.click();
fileLink.remove;
window.URL.revokeObjectURL(fileURL);
}
the problem is that when I try to upload a file and then download it, its content is not parsed correctly (is shown undefined, string in Base64 or numbers depending on how I try to solve it). The file is sent by a post request and is retrieved through an input form bound to an onFileSelected function.
function onFileSelected(e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onloadend = (evt) => {
if (evt.target.readyState === FileReader.DONE) {
var arrayBuffer = evt.target.result;
this.file.content = new Uint8Array(arrayBuffer);
//this.file.content = arrayBuffer;
}
};
}
axios.post(...,document,...)
and I have tried using atob and btoa as well before assigning the value to this.file.content. If I print the file on server Welcome.txt it gives B#ae3b74d and if I use Arrays.toString(welcome.getContent()) it gives an array of numbers but as soon as it passed to the frontend its content become in Base64 welcome: { ... content: IFRoaXMgaXMgYSB0ZXN0IGZpbGUhIAo...}. Any idea? Thank you a lot!

Converting <input type=file> contents to Base64 and sending to Spring method expecting MultiPartFile

Because of server issues I need to convert the contents of a file upload to Base64 before it gets submitted to the server.
I've managed the JS side of things using reader.readAsDataURL to get the contents into Base64 in a local JS variable. I've then tried creating a new FormData and setting the base64 variable there - it replaces the name of the but then it also replaces the type - it's no longer a but just binary data - so when I send this to the server - I'm getting Spring error typeMismatch.org.springframework.web.multipart.MultipartFile
Basically - any thoughts how to convert file contents to Base64 (done that ok) but send to existing JAVA method with Spring MultiPartFile?
i.e. without me rewriting and adding extra fields in the FormData for file name and size etc (the stuff I'd get using the MultipartFile on the server end).
JS: (error handling removed)
var input = $(".actualFileInput");
var files = null;
// File data
if (input[0].files.length > 0) {
files = input[0].files;
}
var file = files[0], reader = new FileReader();
reader.onloadend = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
var name = input.attr('name');
input.attr('name', '');
var newFormData = new FormData(form); // New form with all data from the existing one
newFormData.set('uploadFile',b64); // replace with the base64 value of the selected file
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
request.open(form.method, form.action, true);
request.onload = function() {
var url = window.location;
input.attr('name', name);
request.send(newFormData);
};
reader.readAsDataURL(file);
The Java at the server end:
#RequestMapping(method = RequestMethod.POST, params = "upload")
public String upload(#ModelAttribute("uploadDocument") UploadDocument document, BindingResult result,
ModelMap model, HttpServletRequest request, SessionStatus status) throws Exception {
UploadDocument is:
public class UploadDocument implements Serializable {
private static final long serialVersionUID = -3534003705995293025L;
// File upload work area
private MultipartFile uploadFile = null;
private String fileComment = null;
private Integer fileTypeId = null;
... (other fields in the <form>)
All the JAVA stuff works fine if I just submit the form. But in JS reading the file contents as Base64 then sending as a field doesnt get translated to MultiPartFile. Change to byte[] and add new fields for the file metadata myself? Or is there some trick I'm missing.
Thanks folks.
The way to make this JS variable send to a Spring MultiPartFile is:
newFormData.set('uploadFile',new Blob([b64]),files[0].name); // replace with the base64 value of the selected file
i.e. make it a blob, and 3rd arg is the file name the user selected in . This now sends the base64 value of the file contents.

Decode Javascript FileReader Base64 in C#

I have the following Javascript-Code for Converting a file into base64:
File.prototype.convertToBase64 = function (callback) {
var FR = new FileReader();
FR.onload = function (e) {
callback(e.target.result)
};
FR.readAsDataURL(this);
}
an example output would be:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj [...] /j+vigYmLtYx9n0tGzJIyZKIzsYyRRWj0RfdWtCiQdF9rH8f18SMciL7X8DJMySJ8uC4JDRWjH8CEiitULVaMf68GQYn2PvskyciSs26tDWr0ooorsWi0WiFIei0Y/10QkQkWWXo+xaNjetdjHo9YlFdi1eiell6LRj/AGIshIUjcKRej1Ws
But I can't decode it with this:
byte[] data = Convert.FromBase64String(base64Image);
It says that it can't recognize the layout of the data. How can I decode the base64 data coming from FileReader in JS in C#?
Thanks to Thomas I found a solution.
The C#-Decoder doesn't like the header: data:image/jpeg;base64,
You can fix it with this short code:
int index = base64Image.IndexOf("base64,") + "base64,".Length;
string base64String = base64Image.Remove(0, index);

How to posting Images bytes from javascript to JAX-RS websevice and create BufferedImage from imageBytes array?

I would like to send image bytes from a Javascript client to a JAX-RS web service. I tried encoding the image bytes using the Javascript btoa() function, and at server-side tried to create a BufferedImage like
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(imageBytes);
BufferedImage originalImage = ImageIO.read(arrayInputStream);
However, originalImage is getting as null.
Could you please help me.
Full Code:
Javascript:
function handleUpload(){
var input = document.getElementById("imageUploadId");
var file = input.files[0];
file.convertToBase64(base64ImageData);
}
function base64ImageData(data){
if(data){
var imageBytes = data.split(",")[1];
imageBytes = btoa(imageBytes);
}
}
Java - Jax-RS :
String ImageByteFromrequest ="";
byte[] imageBytes = Base64.decode(ImageByteFromrequest);
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(imageBytes);
BufferedImage originalImage = ImageIO.read(arrayInputStream);
Thanks in advance.

Pass PNG on form submit, Request URL Too long

So I have an interesting question. I have a form where a user draws an image on a canvas (think a signature pad). I then need to send the image to my C# Controller (I am using ASP.NET MVC 5). The code I have functions for shorter strings, but when I try to pass the PNG data, it is too long and I recieve a HTTP Error 414. The request URL is too long error. Here is my code:
Html:
<form id="mainForm" action="submitUserAnswer" method="post">
<input type="hidden" id="userOutput" name="output" value="" />
//...other form elements, signature box, etc.
</form>
Javascript:
function goToNextQuestion() {
var output = $('#signature').jSignature("getData");
$('#userOutput').val(output);
$('#mainForm').submit();
}
C#:
public ActionResult submitUserAnswer()
{
//use the userOutput for whatever
//submit string to the database, do trigger stuff, whatever
//go to next question
System.Collections.Specialized.NameValueCollection nvc = Request.Form;
string userOutput = nvc["output"];
ViewBag.Question = userOutput;
return RedirectToAction("redirectToIndex", new { input = userOutput });
}
public ActionResult redirectToIndex(String input)
{
ViewBag.Answer = input;
return View("Index");
}
My png data is very long, so the error makes sense. My question is how can I get the png data back to my controller?
Maybe you just need to increase allowed GET request URL length.
If that doesn't works I have an aspx WebForm that saves a signature, and I use a WebMethod
[ScriptMethod, WebMethod]
public static string saveSignature(string data)
{
/*..Code..*/
}
and I call it like this:
PageMethods.saveSignature(document.getElementById('canvas').toDataURL(), onSucess, onError);
also I have to increase the length of the JSON request and it works fine, with no problems with the lenght.
In MVC there isn't WebMethods, but JSON and AJAX requests do the job, just save the data in a session variable, and then use it when need it.
Hope it helps
You have error because your data is string (base64) and have max limit for send characters, better way is to create blob (png file) from base64 at client side, and send it to server. Edit. All listed code here, exists in stackoverflow posts.
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = null;
// TypeError old chrome and FF
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder;
if(window.BlobBuilder){
var bb = new BlobBuilder();
bb.append(ab);
blob = bb.getBlob(mimeString);
}else{
blob = new Blob([ab], {type : mimeString});
}
return blob;
}
function sendFileToServer(file, url, onFileSendComplete){
var formData = new FormData()
formData.append("file",file);
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = onFileSendComplete;
xhr.send(formData);
}
var base64 = $('#signature').jSignature("getData");
var blob = dataURItoBlob(base64);
var onComplete = function(){alert("file loaded to server");}
sendFileToServer(blob, "/server", onComplete)

Categories