Angular:将Blob转换为pdf [英] Angular : converting blob into pdf
问题描述
我的component.ts:
export class AppComponent {
constructor(private httpClient: HttpClient) {}
tag: string;
selectedFile: File;
retrievedFile: any;
base64Data: any;
retrieveResonse: any;
message: string;
UserTag: any;
//Gets called when the user selects a file
public onFileChanged(event) {
//Select File
this.selectedFile = event.target.files[0];
}
//当用户单击提交"以上传文件时被调用
onUpload() {
console.log(this.selectedFile);
//FormData API提供了一些方法和属性,使我们可以轻松地准备要通过POST HTTP请求发送的表单数据.
const uploadImageData = new FormData();
uploadImageData.append("file", this.selectedFile, this.selectedFile.name);
uploadImageData.append("tag", this.tag);
//Make a call to the Spring Boot Application to save the file
this.httpClient
.post("http://localhost:8080/do", uploadImageData, {
observe: "response"
})
.subscribe(response => {
if (response.status === 200) {
this.message = "Image uploaded successfully";
} else {
this.message = "Image not uploaded successfully";
}
});
}
//当用户单击检索文件"按钮以从后端获取图像时被调用
getFile() {
//Make a call to Spring Boot to get the file Bytes.
this.httpClient
.get("http://localhost:8080/get/" + this.UserTag)
.subscribe(res => {
this.retrieveResonse = res;
this.base64Data = this.retrieveResonse.fileContent;
if (
this.retrieveResonse.fileType == "jpg" ||
this.retrieveResonse.fileType == "png" ||
this.retrieveResonse.fileType == "jpeg"
) {
this.retrievedFile = "data:image/jpg;base64," + this.base64Data;
}
if (this.retrieveResonse.fileType == "pdf") {
var blob = new Blob([this.base64Data], { type: "application/pdf" });
this.retrievedFile = blob;
}
});
}
}
get方法:
public DBFile getFile( String fileTag) throws IOException {
final Optional<DBFile> retrievedFile = fileRepo.findByFileTag(fileTag);
DBFile img = new DBFile(retrievedFile.get().getName(), retrievedFile.get().getFileType(),
decompressBytes(retrievedFile.get().getFileContent()),retrievedFile.get().getAddedAt(),retrievedFile.get().getFileTag());
解压缩方法: //解压缩文件字节,然后再将其返回到角度 应用
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
return img;
}
我的组件.HTML
<div class="container row">
<div class="col-md-12">
<h1>Upload Image</h1>
</div>
</div>
<div class="container row">
<div class="col-md-6">
<input type="file" (change)="onFileChanged($event)" />
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form">tag</label>
<input
type="text"
class="form-control"
id="tag"
[(ngModel)]="tag"
required
/>
</div>
</div>
<div class="col-md-6">
<input type="button" (click)="onUpload()" value="upload" />
</div>
</div>
<hr />
<div class="container row">
<div class="col-md-12">
<div *ngIf="message">{{ message }}</div>
</div>
</div>
{{ this.retrieveResonse | json }}
<div class="container row">
<div class="col-md-6">
<input
type="text"
class="form-control"
id="name"
placeholder="File Tag"
[(ngModel)]="UserTag"
name="name"
/>
</div>
<div class="col-md-6">
<input type="button" (click)="getFile()" value="Get File" />
</div>
</div>
<div class="container row">
<div class="col-md-12">
<div>
<pdf-viewer
[src]="retrievedFile"
[render-text]="true"
style="display: block;"
></pdf-viewer>
</div>
</div>
</div>
控制台错误: 控制台错误照片
有需要帮助的人吗?..
您无法在pdf查看器中将blob文件作为src传递,您必须将其转换为safeUrl才能进行预览.希望这会有所帮助.
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; // import
constructor(private sanitizer: DomSanitizer) // include in constructor
if (this.retrieveResonse.fileType == "pdf") {
var blob = new Blob([this._base64ToArrayBuffer(this.base64Data)], {
type: "application/doc"
});
const url = URL.createObjectURL(blob);
this.retrievedFile = window.open(url);
base64ToArrayBuffer方法:
_base64ToArrayBuffer(base64) {
const binary_string = window.atob(this.base64Data);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
i created a SPRING BOOT service which can store different type of files. when i tried to consume this service into ANGULAR , the images works as well but when i try to display the pdf files with ng-pdf-viewer it doesn't work for me.
my component.ts:
export class AppComponent {
constructor(private httpClient: HttpClient) {}
tag: string;
selectedFile: File;
retrievedFile: any;
base64Data: any;
retrieveResonse: any;
message: string;
UserTag: any;
//Gets called when the user selects a file
public onFileChanged(event) {
//Select File
this.selectedFile = event.target.files[0];
}
//Gets called when the user clicks on submit to upload the file
onUpload() {
console.log(this.selectedFile);
//FormData API provides methods and properties to allow us easily prepare form data to be sent with POST HTTP requests.
const uploadImageData = new FormData();
uploadImageData.append("file", this.selectedFile, this.selectedFile.name);
uploadImageData.append("tag", this.tag);
//Make a call to the Spring Boot Application to save the file
this.httpClient
.post("http://localhost:8080/do", uploadImageData, {
observe: "response"
})
.subscribe(response => {
if (response.status === 200) {
this.message = "Image uploaded successfully";
} else {
this.message = "Image not uploaded successfully";
}
});
}
//Gets called when the user clicks on retrieve filebutton to get the image from back end
getFile() {
//Make a call to Spring Boot to get the file Bytes.
this.httpClient
.get("http://localhost:8080/get/" + this.UserTag)
.subscribe(res => {
this.retrieveResonse = res;
this.base64Data = this.retrieveResonse.fileContent;
if (
this.retrieveResonse.fileType == "jpg" ||
this.retrieveResonse.fileType == "png" ||
this.retrieveResonse.fileType == "jpeg"
) {
this.retrievedFile = "data:image/jpg;base64," + this.base64Data;
}
if (this.retrieveResonse.fileType == "pdf") {
var blob = new Blob([this.base64Data], { type: "application/pdf" });
this.retrievedFile = blob;
}
});
}
}
the get method:
public DBFile getFile( String fileTag) throws IOException {
final Optional<DBFile> retrievedFile = fileRepo.findByFileTag(fileTag);
DBFile img = new DBFile(retrievedFile.get().getName(), retrievedFile.get().getFileType(),
decompressBytes(retrievedFile.get().getFileContent()),retrievedFile.get().getAddedAt(),retrievedFile.get().getFileTag());
the decompress method: // uncompress the file bytes before returning it to the angular application
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
return img;
}
my component.HTML
<div class="container row">
<div class="col-md-12">
<h1>Upload Image</h1>
</div>
</div>
<div class="container row">
<div class="col-md-6">
<input type="file" (change)="onFileChanged($event)" />
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form">tag</label>
<input
type="text"
class="form-control"
id="tag"
[(ngModel)]="tag"
required
/>
</div>
</div>
<div class="col-md-6">
<input type="button" (click)="onUpload()" value="upload" />
</div>
</div>
<hr />
<div class="container row">
<div class="col-md-12">
<div *ngIf="message">{{ message }}</div>
</div>
</div>
{{ this.retrieveResonse | json }}
<div class="container row">
<div class="col-md-6">
<input
type="text"
class="form-control"
id="name"
placeholder="File Tag"
[(ngModel)]="UserTag"
name="name"
/>
</div>
<div class="col-md-6">
<input type="button" (click)="getFile()" value="Get File" />
</div>
</div>
<div class="container row">
<div class="col-md-12">
<div>
<pdf-viewer
[src]="retrievedFile"
[render-text]="true"
style="display: block;"
></pdf-viewer>
</div>
</div>
</div>
console error: photo of the console error
any help guys please?..
You cant pass the blob file as src in pdf viewer, you have to convert it to safeUrl to preview. Hope this will help.
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; // import
constructor(private sanitizer: DomSanitizer) // include in constructor
if (this.retrieveResonse.fileType == "pdf") {
var blob = new Blob([this._base64ToArrayBuffer(this.base64Data)], {
type: "application/doc"
});
const url = URL.createObjectURL(blob);
this.retrievedFile = window.open(url);
the base64ToArrayBuffer methods:
_base64ToArrayBuffer(base64) {
const binary_string = window.atob(this.base64Data);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
这篇关于Angular:将Blob转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!