converting image source into file and append the file in rest api - angularjs

I have an image source , i need to convert it into png file and append it to backend and send. upload is successfull ,but when we retrieve the stored file from backend , it has invalid file format error. I think it was not converted to base64 and because of this we have this issue. I am using $base64 dependency to covert my source.
source = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xjy9Z6xlaXYdts6999ycc3o5p6pXVV3V1Xl6unt62CI5nCFFw6RoyIZtSDIMWTb8wyBk2DBgyYZ/CIT+SJRJGDJNWrboiRRnunu6OR0qp5fq5XRzzjkcY+03ozcoVNebV/eee8639157rbV3Kf/kj35XazbbsFrtqJSa2Ns9Qj5XQa8LOOw+mE0O1Kt9WCxOVCtN5HMlmMx=="
$scope.uploadFile = function(source){
var imageBase64 = $base64.encode(source);
var blob = new Blob([imageBase64], {
type: 'image/png'
});
var filename = Math.random().toString(36).substring(7);
var file = new File([blob], filename + '.png',{type:'image/png'});
$scope.file = file;
var json = {
"json": {
"request":{
"servicetype":"4",
"functiontype": "4012",
"session":{
"sessionid":session
}
}
}
};
fileUpload.uploadFileToEmp( json, file ).then(function(res){
}
}
});
}

Related

How can i generate a blob url?

I have a function that will determine if the gif is animated or non-animated. Everything is working fine, until i upload those gif to the server, and load it, the blob url is a empty string. How can i generate a blob url for this?
Due to the blob url being empty string, i get parameter 1 is not of type 'blob'
The function below determines if the gif is animated or not.
$scope.isNotAnimatedGIF = function(file) {
var reader = new FileReader();
return new Promise(function(resolve, reject) {
reader.onload = function (e) {
var gifInfo = gify.getInfo(reader.result);
if (gifInfo.images.length <= 1) {
file.animatedGIF = false;
resolve(true);
} else {
file.animatedGIF = true;
resolve(false);
}
}
reader.readAsArrayBuffer(file);
});
}
I am using Angular 1.4.10
Thank you !
You can use URL.createObjectURL() to create Blob url.
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
DEMO
function createbloburl(file, type) {
var blob = new Blob([file], {
type: type || 'application/*'
});
file = window.URL.createObjectURL(blob);
return file;
}
document.querySelector('#file').addEventListener('change', function(e) {
var file = e.currentTarget.files[0];
if (file) {
file = createbloburl(file, file.type);
document.querySelector('iframe').src = file;
//console.log(file)
}
})
<input id="file" type="file">
<iframe src=""></iframe>
try this reader.readAsDataURL(Blob|File).
you can find more from here

Encode PDF to base64 in ReactJS

Please help me!
How can I encode file to string base64 in react
handleUploadFile(event) {
let file = event.target.files[0]
// here encoding file base64?
this.setState({
fileData: file,
fileName: file.name
})
}
Here is what you can try out :
handleUploadFile(event) {
let selectedFile = event.target.files;
let file = null;
let fileName = "";
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
let fileToLoad = selectedFile[0];
fileName = fileToLoad.name;
// FileReader function for read the file.
let fileReader = new FileReader();
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
file = fileLoadedEvent.target.result;
// Print data in console
console.log(file);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
this.setState({
fileData: file,
fileName: fileName
})
}
You may need to change it for multiple files though.

Unable to open PDF while converting it from a HTML in react

I am getting an html file from a backend application and now saving it in pdf format in react. However, unable to open it in adobe :(
CreateFile(data, contentType) {
let file;
if (contentType === "text/html") {
// file = new Blob([data], { type: contentType });
file = new Blob([new Uint8Array(data)], { type: contentType });
}
saveDocument() {
let contentType = "application/pdf";
let file = this.createFile(data,
contentType.toLowerCase());
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // others apart from Safari and Opera mini
var a = document.createElement("a"),
url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
can anyone help?
I suggest you using a library like wkhtmltopdf in your backend to convert the html into pdf before sending it.

Binary files corrupted - How to Download Binary Files with AngularJS

download any file using ResponseEntity with angular does not work
I need to download a file using angular in client side,
this file can have any format it could be a pdf or excel or image or txt ...
my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.
so in my controller here is the function that calles the service method:
vm.downloadFile = downloadFile;
function downloadFile(file){
var urlDir = "C://STCI//"+idpeticion;
return VerDocServices.downloadFile(file,urlDir)
.then(function(response) {
var data = response.data;
var filename = file;
var contentType = 'application/octet-stream';//octet-stream
var linkElement = document.createElement('a');
try {
var blob = new Blob([ data ], {
type : contentType
});
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
var clickEvent = new MouseEvent("click", {
"view" : window,
"bubbles" : true,
"cancelable" : false
});
linkElement.dispatchEvent(clickEvent);
} catch (ex) {
console.log(ex);
throw ex;
}
}).catch(function(response) {
alert('Se ha producido un error al exportar del documento');
console.log(response.status);
throw response;
});
}
and my service.js has:
angular.module('mecenzApp').service('VerDocServices',['$http',function($http) {
this.downloadFile = function(file,urlDir) {
return $http.get('api/downloadFile', {
params : {
file : file,
urlDir : urlDir
}
}); }} ]);
And my service method is this:
#GetMapping("/downloadFile")
#Timed
public ResponseEntity<byte[]> downloadFile(#RequestParam(value = "file") String file, #RequestParam(value = "urlDir") String urlDir) {
log.debug("GET ---------------- DOWNLOAD FILE : {}", file);
log.debug("GET ---------------- From the DIRECTORY: {}",urlDir);
InputStream fileStream;
String filepath = urlDir+File.separator+file;
try {
File f = new File(filepath);
log.debug("GET ---------------- FILE: {}",f.getPath());
fileStream = new FileInputStream(f);
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
String filename = file;
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
fileStream.close();
return response2;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
could you plz take a look and tell me what did I have missed??
Thank youuu :)
How to Download Binary Files with AngularJS
When downloading binary files, it is important to set the responseType:
app.service('VerDocServices',['$http',function($http) {
this.downloadFile = function(url, file, urlDir) {
var config = {
//SET responseType
responseType: 'blob',
params : {
file : file,
urlDir : urlDir
}
};
return $http.get(url, config)
.then(function(response) {
return response.data;
}).catch(function(response) {
console.log("ERROR: ", response.status);
throw response;
});
};
}]);
If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.
For more information, see MDN Web API Reference - XHR ResponseType
I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:
//your $http(request...)
.success(function (data, status, headers, config) {
//Recieves base64 String data
var fileName = 'My Awesome File Name'+'.'+'pdf';
//Parsing base64 String...
var binaryString = window.atob(data);
var binaryLen = binaryString.length;
var fileContent = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
fileContent[i] = ascii;
}
var blob = new Blob([fileContent], { type: 'application/octet-stream' }); //octet-stream
var fileURL = window.URL.createObjectURL(blob);
$sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
//Creating the anchor download link
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach it to the document
anchor.attr({
href: fileURL,
target: '_blank',
download: fileName
})[0].click();
anchor.remove(); // Clean it up afterwards
})
//.error(function(...
And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:
#POST
#Path("/downloadfile")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(...){
String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
return Response.ok(base64String).build();
}

Encode MP3 file to base64 string in Ionic

I'm working on a app that use cordova-plugin-media to record and audio file, and now I want to encode this file to base64 string, for now I can locate the file but when I try to encode it I get this :
"{"$$state":{"status":0}}"
Here is my code
audio.stopRecord();
audio.play();
if(device.platform == "iOS")
{
var path = cordova.file.tempDirectory;
}
else if(device.platform == "Android")
{
var path = cordova.file.externalRootDirectory;
}
var filename = name + extension;
var filepath = path + filename;
console.log(filepath);
console.log(JSON.stringify($cordovaFile.readAsDataURL(path, filename)));
file path : file:///storage/emulated/0/tPUhcxUKhmLUrWK3Qkqhc69OxeEIWyYrhEB0he9OwM0ffmjY2OUh3TLbFTsApdpIpjxyuC2wouyCs6m7uvdOCHCMiw9mbLMGYM25.mp3
Can any one help me with this??
Thanks
readAsDataURL needs a file object, it won't work with a string path.
Give the following code a try, working on iOS and Android
window.resolveLocalFileSystemURL(path, function(fileEntry) {fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var base64String = evt.target.result;
};
reader.readAsDataURL(file);
});}, function(e){console.log("error:" + JSON.stringify(e));});

Resources