Sending file to server from a HTML input file - javascript

I have a web page where I upload file from an input type file HTML element.
Then I need to send that file by Url with Ajax to a Java server to a REST web service where it will be processed.
I tried FileReader().readAsDataURL function in javascript, file is encoded in base64 then sent to server by url. But when I try to decode it in Java, it fails.
How can I achieve this ?
My code client-side :
var file = document.getElementById('add_attach').files[0];
var filename = document.getElementById('add_attach').value;
if (file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var name = encodeURIComponent(filename);
var file_content = e.target.result;
//Ajax request to server with sending file_content
};
}
My code server-side :
file_content = file_content.substring(file_content.indexOf("base64"));
file_content = file_content.replace("base64,", "");
byte[] decodedBytes = Base64.getDecoder().decode(file_content);
The errror I get :
java.lang.IllegalArgumentException: Illegal base64 character 20

Related

Decode Javascript packed binary data at server PHP side

I have HTML form with 2 controls - file input control #resume and submit button #action_cv.
Most of files I can (and want) upload to server are binary.
There is reading and packing (encoding) this data at front side (Javascript):
function readFile(file, callback) {
let reader = new FileReader();
reader.onload = callback;
reader.readAsArrayBuffer(file);
}
$(document).ready(function () {
$('#action_cv').on('submit', function (event) {
let input_data = {
resume: null,
resume_data: null
};
let resume = null;
if (($("#resume"))[0].files.length > 0) {
resume = ($("#resume"))[0].files[0];
input_data['resume'] = resume.name;
readFile(resume, function (evt) {
let data = evt.target.result;
let bs =
String.fromCharCode.apply(null, new Uint8Array(data));
input_data['resume_data'] = bs;
});
}
// AJAX call with input_data skipped here...
})
});
Here data contains raw binary data from file, and bs - already packed for AJAX submission to server written by PHP. My question is very simple - how to unpack this encoded (packed) binary in PHP to get original file at server side? (No need to provide writing file operation - it seems evident)

How can I send the POST request to the other server binding file into formdata

I have a pdf file which is generated into my local server with my server side code. I want to send a request to the another server requesting POST. The post method take parameter as FormData where formdata types
one is string and another is file type.
content-type
form-data
Body
 PDF file (file type)
string value
 
Is it possible to make the POST request without browsing the file location?
Doing some R&D I have overcome this problem with following some steps, as there is no way to get the file object from the physical location automatically in client side (basically in js) except browsing for security reason.
In my local server I have created a REST service. which response base64 string of the desired file.
Than I call the REST api from my javaScript and as a response I receive the base64 string. And than I convert it into bytes array and than Blob object and than File object.
base64 string==>bytes array==>Blob object==>File object
var base64 = this.getpdfFromLocal() //get the base64 string
var byteArray= this.base64ToByte(base64 );
var file = this.getFileFromByteArray(byteArray);
//return the byte array form the base64 string
MyApi.prototype.base64ToByte= function(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
};
MyApi.prototype.getFileFromByteArray=function(byteArray) {
var blob = new Blob([byteArray]);
var file = new File([blob], "resource.pdf");
return file;
};
Lastly I make from data using file object and send request the another server REST web services.
var formdata = new FormData();
formdata.append("some_value", "Some String");
formdata.append("file", file);
var url = "http://yoururl.com";
var result =$.ajax({
url : url ,
type : 'POST',
data : formdata,
contentType : false,
cache : false,
processData : false,
scriptCharset : 'utf-8',
async : false
}).responseText;

Decode Base 64 audio file Mp3 into playable Mp3

I am converting the audio MP3 file and storing it as base64 in database using WEB API, now I am fetching the base64 file using ajax and I am getting the base64, the problem is how can I convert the base64 file back to mp3 file and play it using JavaScript.
This if for demo I am using input file, I am getting base64 file from server
<input type='file' onchange='openFile(event)' id="EdituserProfileImage">
var fileName;
var filetype;
var filesize;
var VoiceBase64;
var openFile = function (event) {
var input = event.target;
fileName = input.files[0].name;
filetype = input.files[0].type;
filesize = input.files[0].size;
console.log(input);
console.log(fileName);
var reader = new FileReader();
reader.onload = function (evt) {
var voiceInBinay = evt.target.result;
VoiceBase64 = btoa(voiceInBinay);
contvertBase64toBinaray(VoiceBase64);
};
reader.readAsBinaryString(input.files[0]);
};
This function "contvertBase64toBinaray" using for converting base64 to Binary, I have binary file, need to save as mp3 from this below binary
function contvertBase64toBinaray(VoiceBase64) {
var audiofile = atob(VoiceBase64)
};
Use window.atob function to decode your base 64 data.
This question shows you how you can play the mp3 in JS.

window.btoa not working for PNG and JPEG files

I convert file that are uploaded on the GUI and decoded it on the server which is a node.js server. Following code works fine for PDF files etc. but does not work for Image files ( PNG and JPEG). Following is the code :-
var fileName = form.findField("attachment").fileInputEl.dom.files[0];
var fileReader = new FileReader();
fileReader.onload = function (olEvent) {
var payload = window.btoa(unescape(encodeURIComponent(olEvent.target.result)));
contactObj['file_content'] = payload;
contactObj['file_name'] = fileName.name;
contactObj['file_type'] = fileName.type;
contactObj['file_size'] = fileName.size;
contactObj['fileAttached'] = fileAttached;
me.postContactUs(contactObj);
};
fileReader.readAsBinaryString(fileName);
}
on the node server using an npm (base-64) to decode this. Any ideas??

Cannot convert to System.Byte

I am using trying to send an ajax post request with some text & files. However the accepted file format is base64binary (it is specified by the api to accept the post request)
Am using the below javascript function to convert the image file to a base64:
function encodeImageFileAsURL(){
var filesSelected = document.getElementById("image").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
convertedimage = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
//alert("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
And using a simple ajax call to send the data.
This is the response I am getting from the api:
Cannot convert data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAZDElEQVR4nO3deXhV5Z0H8O/vnJsElE1LRRYd0FqXoK3FEbKo6YxLccFWvZCAC0uWoi3aqe10pu0Y22qn1qVVUUkIWgWSEO1Y6IiK9sGaBbRoRVDbqYoiqBVUQCDLPec3f4AtUsDce5b33Hu+n+fxDx9z3vcr5Hzve5Z7DkBERERERERERERERERERERERERERERERERERERERBElpgOQ/wqTi/IH5m0dCsc9TIDBKtZgAQYrdDCAwbt+SkREB+29rSpcAFt2/6sjwCYFNilkk6hssoB3exLu5pXHbNiI2lo3tP8pCgQLIEsVJW/ta+f1P8FxUCiCo0QwSoGRUIwCMByAFXCEbgBvimCdqrwu0HUAXrUc+0X7vTf/vHx5bSrg+ckHLIAscOrlv/qM3dVVBJGTLcGJCpwExecA2Kaz7UcXgJcAXSMqL4rg2YPyCp59/IHLt5sORp/EAoigooo5x0HtYoFbAkgRgOOQ/X9XKQB/BNAuQLvrpFo7WmZuMB0q7rL9lyonlJQ3DFO454vgTFV8GX87Ts9tCrwuwDJVecJN9Hls5YJLt5rOFDcsAEPGld890tZEUi2cD0UxgITpTCYpsF2gy0Wsh3vy8v7nmfuv2Gw6UxywAEJUkmw4Vm23QkWTonKC6TwR5grQ4aq2pNy85mdbpr1jOlCuYgEEbMwFcw7q089OqqIS0BLwzzxd3QCWAlI/3BnwaEvLRMd0oFzCX8aAjJtYd6ZtS7UqLgDQx3SeHPEugGYRrWtrrF5rOkwuYAH4aEz1nLz8bdYlULlaoGNN58lhDoClCvlFR1Plk6bDZDMWgA/KKuYM7lbrGwBmAjjMdJ6Y+Yuq3tm9Q+tXLanZYTpMtmEBeFCUvHu4JPK+A+h0KPqbzhNzGwG9Pd/pmb285aqPTIfJFiyADJyerB+VsvV... to System.Byte.
Parameter name: type ---> Input string was not in a correct format.
Would anyone tell me about the way or approach to fix this?
Thank you in advance.

Categories

Resources