How to convert an heic image to jpg/png in angular 6 - angular6

In my application user can upload image from his/her mobile device. Since i am facing problem in converting HEIC image to jpg.
Application create its thumbnails too.
While searching on google i found "https://github.com/alexcorvi/heic2any". which helped me a little. But here i have to enter the physical path of the like -> fetch('path/to/image.heic') this. But in angular we handle file upload like -> event.target.files[0] on file upload.
fetch('path/to/image.heic')
.then((res) => res.blob())
.then((blob) => heic2any({ blob }))
.then((conversionResult) => {
console.log(conversionResult);
})
.catch((e) => {
console.log(e);
});
Since i am implementing this in angular, How i am reading the file object is like this
handle(event) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
console.log(event);
}
console.log(reader.readAsDataURL(event.target.files[0]));
}
}
How to proceed so that i can save image in jpg format in my backend(laravel 5.2).
Thanks

Related

Upload zip files in angular 8

I am trying to implement zip file upload functionality in Angular 8 app. 3 conditions that I need to satisfy are:
1. Only allow zip files to be uploaded else throw error message
2. File size should not cross 3 MBs else throw error message
3. When I choose zip file, it should show progress bar but file should only be uploaded via REST API call when I click 'Register' button separately.
What I have implemented so far is:File Upload Service
postFile(fileToUpload: File, header): Observable<any> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
if (fileToUpload.size <= 3048576)
return this.httpClient.post(endpoint, formData, { headers: header })
.pipe(map(data => {
console.log(data);
return data;
},error => {
console.log(error, 'reduce file size');
}))
}
Component TS File
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload, this.headers).subscribe(data => {
// do something, if upload success
console.log('the file has been uploaded successfully', data);
}, error => {
console.log(error);
});
}
Component HTML
<input type="file"
id="file" (change)="handleFileInput($event.target.files)">
Please suggest how can I modify so that my functionality is as described.
for points 1 and 2 you should add a validation function in your code to check both the file extension and the size.
The upload should be possible only if the file passes the validation.
In addition to that, you should probably return some kind of feedback to the user when the validation fails.
You can track the file upload progress (and show a progress bar) adding additional options to the .post method and listening for specific events
return this.httpClient.post(endpoint, formData, {
headers: header,
reportProgress: true,
observe: 'events'
}).pipe(map(event => {
if (event.type === HttpEventType.Response) {
// upload complete
}
if (event.type === HttpEventType.UploadProgress) {
// the event contains information about loaded data
// you can use event.loaded and event.total to display the progress bar
}
}))

fetching data from json file in assets folder

Trying to fetch data from a json file in ionic 2 application, I am using the below piece of code within constructor for fetching json from assets folder, but getting error "Supplied parameters do not match any signature of call target." What i am missing, Please suggest.
this.http.get('assets/sample.json')
.map((res) => res.json().records)
.subscribe(data => {
this.data = data;
console.log("json data"+ data);
}, (rej) => {console.error("Could not load local data",rej)});
So I solved it, the path of json file from assets folder used as below help me to get the answer that displayed the data on device.
this.http.get('/android_asset/www/assets/data/subjects.json').map(res => res.json()).subscribe(
response => {
this.posts = response;
console.log(this.posts);
},
err => {
console.log("Oops!");
});
While if we use /assets/data/subjects.json, this will display the data on browser, though we can not use a single path that could be able to get the data on both browser as well as on device, because both have the different file system so we need different way to access the data on the devices.
this.http.get("assets/sample.json")
.subscribe(res =>{
this.data=res.json();
this.data=Array.of(this.data);
console.log(this.data);
}, error =>{
console.log(error);
});
Try this.

Convert CSV to JSON client side with React DropZone

From React dropzone, i receive a File object with a File.preview property whose value is a blob:url. i.e. File {preview: "blob:http://localhost:8080/52b6bad4-58f4-4ths-a2f5-4ee258ba864a"
Is there a way to convert this to json on the client? The file isnt need to be stored in a database (the convert JSON will be). I've attempted to use csvtojson but it's unable to use the file system as it uses node to power it. Ideally would like to convert this in the client if possible, once user has uploaded it. Any suggestions welcomed.
<Dropzone
name={field.name}
onDrop={(acceptedFiles, rejectedFiles) => {
acceptedFiles.forEach(file => {
console.log(file)
let tempFile = file.preview
csv()
.fromSteam(tempFile) // this errors with fs.exists not a function as its not running serverside
.on('end_parsed',(jsonArrObj)=>{
console.log(jsonArrObj)
})
})
}}
>
Yes, its possible with FileReader and csv:
import csv from 'csv';
// ...
const onDrop = onDrop = (e) => {
const reader = new FileReader();
reader.onload = () => {
csv.parse(reader.result, (err, data) => {
console.log(data);
});
};
reader.readAsBinaryString(e[0]);
}
// ...
<Dropzone name={field.name} onDrop={onDrop} />
FileReader API: https://developer.mozilla.org/en/docs/Web/API/FileReader
csv package: https://www.npmjs.com/package/csv

How to make a pdf Generator with ionic?

I want to make a pdf of the current page so the user can print it out but every page is dynamic so I will need a sort of a text to pdf generator to make it work.
It is an ionic2 app and is for like a recipe page so you can click on a button and it just makes a pdf out of the text.
Do you guys know how I can achieve that?
Your best bet is probably this plugin:
https://github.com/cesarvr/pdf-generator
give your dynamic page section an id like 'pdf-area' and then select it in your .ts file like this:
let content = document.getElementById('pdf-area').innerHTML
you can then turn that into a file or print it like this
cordova.plugins.pdf.htmlToPDF({
data: content,
type: "base64"
},
(success) => {
// you might have to turn the base64 into a binary blob to save it
// to a file at this point
},
(error) => console.log('error:', error);
);
}
put your html in assets folder and give the html path like this.
In my case this path is working:
var file = 'file:///android_asset/www/assets/lolc.html';
generatePdf(){
const before = Date.now();
document.addEventListener('deviceready', () => {
console.log('DEVICE READY FIRED AFTER', (Date.now() - before), 'ms');
var file = 'file:///android_asset/www/assets/lolc.html';
cordova.plugins.pdf.fromURL(file,{
documentSize: "A4",
landscape: "portrait",
type: "share"
}),
(sucess) => console.log('sucess: ', sucess),
(error) => console.log('error:', error);
});
}

How to use cheerio to get the URL of an image on a given page for ALL cases

right now I have a function that looks like this:
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const src = url + "/" + $("body").find("img")[0].attribs.src;
//make sure there are no extra slashes
resolve(src.replace(/([^:]\/)\/+/g, "$1"));
})
.catch(err => {
reject(err);
});
});
}
this will handle the average case where the page uses a relative path to link to an image, and the host name is the same as the URL provided.
However,
most of the time the URL scheme will be more complex, like for example the URL might be stackoverflow.com/something/asdasd and what I need is to get stackoverflow.com/someimage link. Or the more interesting case where a CDN is used and the images come from a separate server. For example if I want to link to something from imgur ill give a link like : http://imgur.com/gallery/epqDj. But the actual location of the image is at http://i.imgur.com/pK0thAm.jpg a subdomain of the website. More interesting is the fact that if i was to get the src attribute I would have: "//i.imgur.com/pK0thAm.jpg".
Now I imagine there must be a simple way to get this image, as the browser can very quickly and easily do a "open window in new tab" so I am wondering if anyone knows an easy way to do this other than writing a big function that can handle all these cases.
Thank you!
This is my function that ended up working for all my test cases uysing nodes built in URL type. I had to just use the resolve function.
static getPageImg(url) {
return new Promise((resolve, reject) => {
//get our html
axios.get(url)
.then(resp => {
//html
const html = resp.data;
//load into a $
const $ = cheerio.load(html);
//find ourself a img
const retURL = nodeURL.resolve(url,$("body").find("img")[0].attribs.src);
resolve(retURL);
})
.catch(err => {
reject(err);
});
});
}