How to upload PDF file to server using angular 6 - angular6

I generate HTML content to export PDF file using JsPDF library. Now, i need how to pass exported PDF file to server using angular 6. Thanks in advance

Here is my way to do it.
//HTML code
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv"
(change)="changeListener($event)" />
//Component.ts
You have to import StaffService here:
changeListener($event: any) {
this.data = $event.target.files;
this.postFile(this.data);
}
postFile(inputValue: any): void {
this.file = inputValue[0];
this.staffService.uploadCSV(this.file).subscribe(response => {
//Do your next redirection or operation here
}, error =>{});
}
//StaffService.ts
public uploadCSV(file): Observable<any> {
const formdata = new FormData();
formdata.append('files', file);
return this.http.post(environment.apiUrlIp + this.urls.uploadCSVUrl, formdata, {
reportProgress: true,
responseType: 'json'
});
}
Let me know if you find any issue to integrate this code. Happy to help.

Related

Downloading a json file (from json-server) as a txt or json or csv file, in an Angular app

I have installed the json-server in my Angular app which enables me to save a form (filled by the user) via a fake json API into a json file:
{
"extracts": [
{
"contentName": "xxx",
"contentType": "xxx",
"contentToStore": "xxx",
"id": 1
}
]
}
I can also see the results at my http://localhost:3000/extracts
In my html template, my form is submitted:
<form #postForm="ngForm" (ngSubmit)="onSubmitExtractions(postForm.value)">
In the corresponding component, I have written this code:
onSubmitExtractions(postData: Post) {
this
.dbService
.submitExtractions(postData)
.subscribe(
postData => {
this.jsonPosts.push(postData);
}
);
this
.dbService
.downloadExtractions(postData);
}
The first snippet writes to the json file, with this code in the service script:
submitExtractions(post: Post): Observable<Post> {
return this.httpClient.post<Post>(this.apiUrl, post, httpOptions);
}
This works fine and I get the results in a json file (fake json server database) and the second snippet is supposed to download this file whose code in the service script is this:
downloadExtractions(post: Post) {
const blob = new Blob([JSON.stringify(post, null, 2)], { type: 'application/json' });
if (blob) {
this.downloaded = 'The blob contains ' + blob.size + ' byte!';
} else {
this.downloaded = 'The download failed!';
}
}
What am I missing in ths code in order to actually download the json content? How do I download this content as a csv or json or even a text file?
Please try this solution. It is using the same blob just with some constant data.
in html
<a [href]="fileUrl" download="file.txt">DownloadFile</a>
in component.ts
export class AppComponent implements OnInit {
name = 'Angular 5';
fileUrl;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
}
For reference, please visit:
https://stackblitz.com/edit/angular-blob-file-download-text-file?file=app%2Fapp.component.ts

Node.js converting stream of downloaded pdf file to base64 string results in error

In my application I'm downloading previously stored images and pdf documents from amazon s3:
public async downloadFile(file: string): Promise<DownloadedFileType> {
const data = await this.#s3.send(
new GetObjectCommand({
Bucket: process.env.AWS_BUCKET_NAME,
Key: file,
}),
);
return { stream: data.Body, name: file };
}
Problem happens when I try to convert obtained stream in to base64 image (to send it as a "preview" to my front end):
private getBase64FromStream(
stream: Readable,
fileType: string,
): Promise<string> {
return new Promise((resolve, reject) => {
const data: Uint8Array[] = [];
function onData(chunk: Uint8Array): void {
data.push(chunk);
}
stream.on('data', onData);
stream.once('end', () => {
const result = Buffer.concat(data).toString('base64');
const mimeType =
fileType === 'pdf' ? 'application/pdf' : `image/${fileType}`;
resolve(`data:${mimeType}; base64, ${result}`);
stream.off('data', onData);
});
stream.once('error', reject);
});
}
It works fine for images (jpeg, png, etc.), but doesn't work for pdf documents. Rendering such base64 on my frontend results in error:
export function PreviewComponent({
src,
}: IProps): JSX.Element {
const classes = useStyles();
const { dispatch } = useContext(AppContext);
const onImageClick = () => {
dispatch(openImageModalAction(src));
};
const onError = (e: unknown) => {
console.log(e);
};
return (
<img
className={classes.imageWrapper}
src={src}
alt="preview"
onClick={onImageClick}
onError={onError}
/>
);
}
With error being React's SyntheticBaseEvent:
type: "error"
_reactName: "onError"
I have no clue what I'm doing wrong. I know you can convert pdf files to base64. Any help will be greatly appreciated.
You are using an <img> tag for displaying your PDF, but it happens that PDF are not images, so the img tag will NOT support it.
MDN confirms that PDF is not on the list of supported formats for the img tag:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
Try using an embed or iframe tags instead as indicated here:
How to display PDF file in HTML?
See an example for react here:
https://stackblitz.com/edit/react-ts-pgvu9y?file=index.tsx
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
name: 'React'
};
}
render() {
return (
<div>
Displaying a PDF file with React<br/>
embed tag works<br/>
<embed src="https://www.inkwelleditorial.com/pdfSample.pdf" width="800px" height="400px" />
img tag does not work<br/>
<img src="https://www.inkwelleditorial.com/pdfSample.pdf" width="800px" height="400px" />
</div>
);
}
}

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
}
}))

File upload in Angular5

I am trying to upload one or more than one files in my web application.
I have tried with the code and error arising from vData.service.ts file
Error: property 'yoursHeadersConfig' does not exist on VDataservice
property 'catchError' does not exist on 'observable'
property 'HandleError' does not exist on 'VDataservice'
Can you let me know how to resolve the issue and provide an idea for multiple file upload in the web application? I have provided entire relevant code for the issue.
Gist links:
ad.component.html: https://gist.github.com/aarivalagan/ac15e8e2c6f77d0687c01a70e18bca6b
ad:component.ts: https://gist.github.com/aarivalagan/a9c1d22c1d6056da624f0968fb6cd59c
vData.service.ts: https://gist.github.com/aarivalagan/8bfbe47ef8cf0dac267374a8f0ef5b0f
code:
ad.component.html
<div class="form-group col-sm-12">
<label for="usr">Choose file to Upload </label>
<input type="file" multiple formControlName="file" class="form-control" id="file" (change)="handleFileInput($event.target.files)" accept=".pdf,.docx" required>
</div>
ad.component.ts
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
vData.service.ts
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.http
.post(endpoint, formData, { headers: this.yourHeadersConfig })
.map(() => { return true; })
.catchError((e) => this.handleError(e));
}
For catchError use pipe operator
property 'catchError' does not exist on 'observable'
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.http
.post(endpoint, formData, { headers: this.yourHeadersConfig })
.pipe(map(() => { return true; }),
catchError((e) => this.handleError(e)));
}
Error: property 'yoursHeadersConfig' does not exist on VDataservice
property 'HandleError' does not exist on 'VDataservice'
You havent defined these properties in VDataservice, so you can't call those methods using this.
You can try adding below method into VDataservice file:
HandleError(error){
// write your logic to handle error here
}

error in uploading the image from angular to nodejs

My Html file is -
<form method="post" [formGroup]="orderForm" enctype="multipart/form-data" (ngSubmit)="OnSubmit(orderForm.value)" >
<div class="form-group">
<label for="image">Select Branch Image</label>
<input type="file" formControlName="branchImg" (change)="onFileChange($event)" class="form-control-file" id="image">
</div>
</form>
and my .ts file is -
public orderForm: FormGroup;
onFileChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.orderForm.patchValue({
branchImg: reader.result
});
};
}
}
ngOnInit() {
this.orderForm = this.formBuilder.group({
branchImg: [null, Validators.required]
});
}
and then submit the form.
I am supposed to get the image address and the upload that address in cloudinary
But when I am consoling the body in my nodejs app
it gives something like this-
branchImg: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGccAigAYkZCTUQwMTAwMGE4MjBkMDAwMD and so on.
I don't think that it is the images address. Can anyone tell me that what is this? and how to get that image's address which I will upload to cloudinary
As the Eric suggest -
my app.js code is
router.post('/branch',(req,res) =>{
const body = req.body;
const base64Data = body.branchImg.replace(/^data:image\/png;base64,/, "");
console.log(base64Data);
fs.writeFile("out.jpg", base64Data, 'base64', function(err,result) {
console.log(result);
});
});
it gives result as undefined
That basically is a base64 encoding of the image data. What you need to do after you get that is write that to a file, and then upload it to cloudinary
//this will write the base64 data as a jpg file to your local disk
require("fs").writeFile("out.jpg", base64Data, 'base64', function(err) {
//after you write it to disk, use the callback space here to upload said file
//to your cloudinary endpoint
});