Html to Pdf Format Angular - html

Hello i want to convert from html to pdf format and send it as a file to my backend, so i can save it in my server, i tried using jspdf but its not working
SendMail() {
var doc = new jspdf();
doc.fromHTML('<h1>Hello World!</h1>', 20, 20);
var blob = new Blob([doc.output("blob")], { type: "application/pdf" });
let lruta = 'report/' + 'test';
this.uploaderService.uploadfile(blob, lruta).subscribe(
response => {
this.fetcher = response;
this.blockUI.stop();
}, error => {
this.blockUI.stop();
}
);
}
This is my service UploadFile
uploadfile(cabecera, ruta) {
const formData = new FormData();
formData.append('file', cabecera[0]);
formData.append('ruta', ruta);
return this._http.post(this.apiUrl + this.serviceUrl + 'gestion/uploadrevision', formData);
}
When i replace blob with this.file in my this.uploaderService.uploadfile
it works, but i dont want to download and upload my file
file: any;
onFileChange(event) {
this.file = event.target.files;
}

Related

How to check if uploaded file is a JSON file?

I am taking a file input from a user and I want to check if the selected file is a JSON file. How can I do that?
<input type = "file" onChange = {checkJSON}/>
Also how do I retrieve data from the JSON file.
If JSON.parse throws an error, its most likely invalid, therefore you can check if its valid by getting the data into a string and then trying to parse it.
try {
const json = JSON.parse(jsonStr);
} catch (e) {
console.log('invalid json');
}
You can check if file extension is json and be sure that selected file is valid JSON in that way:
function Validate() {
fileName = document.querySelector('#myfile').value;
extension = fileName.split('.').pop();
if (extension != "json")
{
alert("Sorry, " + fileName + " is invalid, allowed extension is json!");
return false;
}
var file = document.getElementById('myfile').files[0];
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = function(evt) {
var jsondata = evt.target.result;
try {
const json = JSON.parse(jsondata);
document.getElementById('jsondata').innerHTML = jsondata;
} catch (e) {
alert("Sorry, " + fileName + " is not valid JSON file!");
return false;
}
}
return true;
};
Html content:
<script src="script2.js"></script>
File: <input type="file" id="myfile" onchange="Validate()"/><br /><br />
<div id="jsondata"></div>
You can play with my little working live demo on ReplIt (both cases - onsubmit and onchange demos)

How am I able to embed a blob video file from an API call in the HTML and play it within the same HTML page?

I am currently having a few methods in the following where handlePdfBlob handles fileType that are in "pdf" while the rest are for other file types where the blob data will be downloaded using handleBlob method. I would like to have a seperate method for fileType that are in "mp4" where the video is not downloaded but being played in the same HTML page upon clicking on a button. I have look at the HTMLVideoElement but I am not sure how am I able to assign the blob data object that is given in the response body of the API to the HTMLVideoElement "video" tag in the HTML file. What are some suggested ways that I am able to achieve playing the video directly in the HTML page after making the API calling from the HTML page?
downloadSampleFile(apiUrl: string, fileName: string, fileType: string, req: any = {}): void {
const options = createRequestOption(req);
this.http.get<Blob>(apiUrl, { params: options, observe: 'response', responseType: 'blob' as 'json' })
.subscribe(((res: HttpResponse<Blob>) => {
if (fileType.match("pdf")) {
this.handlePdfBlob(res.body!, fileName, fileType);
}
else {
this.handleBlob(res.body!, fileName, fileType);
}
}));
}
private handlePdfBlob(data: Blob, fileName: string, fileType: string): void {
const blob = new Blob([data], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
private handleBlob(data: Blob, fileName: string, fileType: string): void {
const blob = new Blob([data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.download = fileName + "." + fileType;
anchor.href = url;
anchor.click();
}
I have tried to create a new method for this and return the URL string.
const url = window.URL.createObjectURL(blob);
However, I am not sure why the url is returning undefined in the console.

Google Document Viewer shows: the server cannot process the request because it is malformed

I try to preview the documents on my site using Google viewer. Document url I get from blob, but when I click to show docs I had an error.
In console I see this link: blob:http://localhost:8080/5372d78d-a9c6-4c50-b23b-249cc643bdd2
const url = window.URL.createObjectURL(
new Blob([response.data], { type: response.data.type })
);
const link = document.createElement("iframe");
console.log(url);
link.src = `https://docs.google.com/viewer?url=${url}&embedded=true`;
link.style.width = "100%";
link.style.height = "500px";
document.getElementById(fileId).appendChild(link);
},```
```async showDoc(file) {
this.fileId = file.Document.Id;
this.fileName = file.Document.Name;
try {
let response = await axios.get(url, {
responseType: "blob",
params: {
fileId: this.fileId,
},
});
this.forceFileShow(response, this.fileId);
console.log("удача", response);
} catch (err) {
console.log("неудача", err.response);
}
}
},
And here html:
<div class="card-icon" #click="showDoc(file)"
:data-target="`#showDoc${file.Document.Id}`"
data-toggle="modal">```
[1]: https://i.stack.imgur.com/tZlkm.png

Ionic 4 : Recording Audio and Send to Server (File has been corrupted)

I would like to record the audio file in mobile application(iOS & Android) and tranfer to server as a formData in ionic 4. I have used the "cordova-plugin-media" to capture the audio using below logics
if (this.platform.is('ios')) {
this.filePaths = this.file.documentsDirectory;
this.fileExtension = '.m4a';
} else if (this.platform.is('android')) {
this.filePaths = this.file.externalDataDirectory;
this.fileExtension = '.3gp';
}
this.fileName = 'recording'+new Date().getHours()+new Date().getMinutes()+new Date().getSeconds()+this.fileExtension;
if(this.filePaths) {
this.file.createFile(this.filePaths,this.fileName,true).then((entry:FileEntry)=> {
this.audio = this.media.create(entry.toInternalURL());
this.audio.startRecord();
});
}
Even I have tried to create the media directly without "File Creation"
I can record and play the audio, but If I am trying to send this file
to server using below logics It won't send properly(corrupted data)
and also web application unable to play .m4a extensions
.
Please correct me If I am doing anything wrong in my code
Upload logic:
let formData:FormData = new FormData();
formData.append('recordID' , feedbackID);
that.file.readAsDataURL(filePath,file.name).then((data)=>{
const audioBlob = new Blob([data], { type: file.type });
formData.append('files', audioBlob, file.name);
that.uploadFormData(formData,feedbackID); //POST Logics -
})
;
I have used the soultion as suggested by Ankush and it works fine.
Used readAsArrayBuffer instead of readAsDataURL.
The .m4a format has supported both ios and android. Also I can
download the the same file from web application.
I am using below code to upload the image to the server. I assume that only a few modifications will be required in this code to transfer media instead of the image file.
private uploadPicture(imagePath: string, apiUrl: string): Observable<ApiResponse<ImageUploadResponseModel>> {
return this.convertFileFromFilePathToBlob(imagePath).pipe(
switchMap(item => this.convertBlobToFormData(item)),
switchMap(formData => this.postImageToServer(formData, apiUrl))
);
}
Rest functions used in above code:
private postImageToServer(formData: FormData, apiUrl: string): Observable<ApiResponse<ImageUploadResponseModel>> {
const requestHeaders = new HttpHeaders({ enctype: 'multipart/form-data' });
return this.http.post<ApiResponse<ImageUploadResponseModel>>(apiUrl, formData, { headers: requestHeaders });
}
private convertBlobToFormData(blob: Blob): Observable<FormData> {
return new Observable<FormData>(subscriber => {
// A Blob() is almost a File() - it's just missing the two properties below which we will add
// tslint:disable-next-line: no-string-literal
blob['lastModifiedDate'] = new Date();
// tslint:disable-next-line: no-string-literal
blob['name'] = 'sample.jpeg';
const formData = new FormData();
formData.append('file', blob as Blob, 'sample.jpeg');
subscriber.next(formData);
subscriber.complete();
});
}
private convertFileFromFilePathToBlob(imagePath: string): Observable<Blob> {
return new Observable<Blob>(subscriber => {
const directoryPath = imagePath.substr(0, imagePath.lastIndexOf('/'));
let fileName = imagePath.split('/').pop();
fileName = fileName.split('?')[0];
this.file.readAsArrayBuffer(directoryPath, fileName).then(fileEntry => {
const imgBlob: any = new Blob([fileEntry], { type: 'image/jpeg' });
imgBlob.name = 'sample.jpeg';
subscriber.next(imgBlob);
subscriber.complete();
}, () => {
subscriber.error('Some error occured while reading image from the filepath.');
});
});
}

compress image on upload in angular

I wanted to upload images to products, and users. So im converting the image to base64 string and sending it. But when the selected image is large, the image is not getting uploaded as the base64 string is too large.
Here is the code:
Html
<input type="file" (change)="onFileSelected($event)">
<button type="submit" title="upload" (click)="uploadImage()"></button>
TS File
onFileSelected(event){
var files = event.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString= btoa(binaryString);
console.log(btoa(binaryString));
}
Im just accepting the images on selection. So, is there any way to comress the image after selection or a way to reduce the base64 string so the image gets uploaded.
Thanks!! in advance.
In Angular you can upload image wihtout converting it into base64. Check this...
import { ViewChild } from '#angular/core';
export class yourComponent {
#ViewChild('fileInput') fileInput;
.
.
.
}
uploadImage(){
let fileBrowser = this.fileInput.nativeElement;
if (fileBrowser.files && fileBrowser.files[0]) {
console.log(fileBrowser.files[0]);
const formData = new FormData();
formData.append("userId", this.userId ); //appending userId in formData
formData.append("image", fileBrowser.files[0]); //appending image in formData
this.apiService.UploadImageMethod(formData)
.subscribe(
response=>{
console.log(response);
if(response.status == 'success'){
console.log(response);
}
},
err => {
this.imageErrorMsg = <any>err.message;
console.log(this.imageErrorMsg);
}
);
}
}
HTML:
<input type="file" id="fileInput" (click)="hideErrorMsg()" accept="image/*" #fileInput>
In API, you can get image data this way. (Php)
UploadImageMethod(){
$fileName = request()->image->getClientOriginalExtension();
$ext = strtolower(request()->image->getClientOriginalExtension());
}
Good Luck!!!