将两个本地存储的PDF上传到REST API

时间:2019-03-18 15:17:36

标签: angular rest spring-boot

我有一个REST API,它带有两个PDF,并从Draftable API返回比较URL。该API已经过测试,可以正常工作。由于我是REST API和Angular的新手,因此在弄清楚如何将两个PDF发送到API时遇到了问题。

这是我测试API的方式:enter image description here

API的一部分:

@PostMapping("/draftableDemo")
    String compareJob(@RequestParam("file1") MultipartFile file1, @RequestParam("file2") MultipartFile file2) {
        CompareJob compareJob = new CompareJob(convert(file1), convert(file2));
        DraftableCompare draftableCompare = new DraftableCompare();
        return draftableCompare.compare(compareJob);
    }

我发现这个SO post存在与我类似的问题。

  • 如何在Angular侧用代表键定义两个PDF?
  • 我是否需要更改API的期望值?
  • 我一直在阅读Angular文件上传器,每个人都在谈论哪个模块?

感谢任何提示,想法或建议!

编辑: 我的HTML:

<div class="content"
     fxLayout="row"
     fxLayout.xs="column"
     fxFlexFill>

    <div fxFlex="50" fxFlex.xs="50" style="position: relative">
        <div>
            <div>
                <p>
                    Open first PDF
                </p>
                <input (change)="onFileSelected(pdf1)" type="file" [multiple]="multiple" id="file1">
            </div>

            <div *ngIf="error" class="error mb">
                {{ error.message | json }}
            </div>

            <div *ngIf="!isLoaded && !error && progressData" id="progress1">
                <div class="bg">
                    <div class="bar" [style.width]="progressData.loaded / progressData.total * 100 + '%'"></div>
                </div>
                <span>{{ getInt(progressData.loaded / progressData.total * 100) }}%</span>
            </div>

            <pdf-viewer [src]="pdfSrc1"
                        [(page)]="page"
                        [rotation]="rotation"
                        [original-size]="originalSize"
                        [fit-to-page]="fitToPage"
                        (after-load-complete)="afterLoadComplete($event)"
                        [zoom]="zoom"
                        [show-all]="showAll"
                        [stick-to-page]="stickToPage"
                        [render-text]="renderText"
                        [external-link-target]="'blank'"
                        [autoresize]="autoresize"
                        [render-text-mode]="renderTextMode"
                        (error)="onError($event)"
                        (on-progress)="onProgress($event)"
                        (page-rendered)="pageRendered($event)"
            ></pdf-viewer>
        </div>
    </div>

    <div fxFlex="50" style="position: relative">
        <div>
            <div>
                <p>
                    Open second PDF
                </p>
                <input (change)="onFileSelected(pdf2)" type="file" [multiple]="multiple" id="file2">
            </div>

            <div *ngIf="error" class="error mb">
                {{ error.message | json }}
            </div>

            <div *ngIf="!isLoaded && !error && progressData" id="progress2">
                <div class="bg">
                    <div class="bar" [style.width]="progressData.loaded / progressData.total * 100 + '%'"></div>
                </div>
                <span>{{ getInt(progressData.loaded / progressData.total * 100) }}%</span>
            </div>


            <pdf-viewer [src]="pdfSrc2"
                        [(page)]="page"
                        [rotation]="rotation"
                        [original-size]="originalSize"
                        [fit-to-page]="fitToPage"
                        (after-load-complete)="afterLoadComplete($event)"
                        [zoom]="zoom"
                        [show-all]="showAll"
                        [stick-to-page]="stickToPage"
                        [render-text]="renderText"
                        [external-link-target]="'blank'"
                        [autoresize]="autoresize"
                        [render-text-mode]="renderTextMode"
                        (error)="onError($event)"
                        (on-progress)="onProgress($event)"
                        (page-rendered)="pageRendered($event)"
            ></pdf-viewer>
        </div>
    </div>

</div>




<hr>
<input type="file" [multiple]="multiple" #fileInput>
<file-upload #fu (change)="fu.upload()" [multiple]="true"></file-upload>
<div class="example-button-row">
    <button mat-raised-button color="primary" routerLink="/draftable" (click)="compareDraftable()">Draftable</button>
    <button mat-raised-button color="primary" routerLink="/pdfcompare">PDF compare</button>
    <button mat-raised-button color="primary">Version3</button>
    <button mat-raised-button color="primary">Version4</button>
</div>

TS:

export class MainComponent implements OnInit {
    // pdfSrc1: string | PDFSource | ArrayBuffer = './assets/fullText2Page.pdf';
    // pdfSrc2: string | PDFSource | ArrayBuffer = './assets/fullText1Page.pdf';

    leftFile: File = null;
    rightFile: File = null;

    @Input() multiple = true;
    @ViewChild('fileInput') inputEl: ElementRef;

    constructor(private http: HttpClient) {
    }

    pdfSrc1: string | PDFSource | ArrayBuffer = '';
    pdfSrc2: string | PDFSource | ArrayBuffer = '';

    pdf1 = 'pdfSrc1';
    pdf2 = 'pdfSrc2';

    error: any;
    page = 1;
    rotation = 0;
    zoom = 1;
    originalSize = false;
    pdf: any;
    renderText = true;
    progressData: PDFProgressData;
    isLoaded = false;
    stickToPage = false;
    showAll = true;
    autoresize = true;
    fitToPage = false;
    outline: any[];
    renderTextMode = 2;

    @ViewChild(PdfViewerComponent) private pdfComponent: PdfViewerComponent;

    ngOnInit(): void {
    }



    /**
     * Render PDF preview on selecting file
     */
    onFileSelected(pdfSource) {
        console.log('Source: ', pdfSource);
        let $pdf: any;

        if (pdfSource === 'pdfSrc1') {
            $pdf = document.querySelector('#file1');
        } else {
            $pdf = document.querySelector('#file2');
        }

        if (typeof FileReader !== 'undefined') {
            const reader = new FileReader();

            reader.onload = (e: any) => {
                if (pdfSource === 'pdfSrc1') {
                    this.pdfSrc1 = e.target.result;
                } else {
                    this.pdfSrc2 = e.target.result;
                }

            };

            reader.readAsArrayBuffer($pdf.files[0]);
        }
    }

    /**
     * Get pdf information after it's loaded
     */
    afterLoadComplete(pdf: PDFDocumentProxy) {
        this.pdf = pdf;
        this.isLoaded = true;
        this.loadOutline();
    }

    /**
     * Get outline
     */
    loadOutline() {
        this.pdf.getOutline().then((outline: any[]) => {
            this.outline = outline;
        });
    }

    /**
     * Handle error callback
     */
    onError(error: any) {
        this.error = error; // set error
    }


    /**
     * Pdf loading progress callback
     */
    onProgress(progressData: PDFProgressData) {
        // console.log('Progress Data: ', progressData);
        this.progressData = progressData;
        this.isLoaded = false;
        this.error = null; // clear error
    }

    getInt(value: number): number {
        return Math.round(value);
    }

    /**
     * Page rendered callback, which is called when a page is rendered (called multiple times)
     */
    pageRendered(e: CustomEvent) {
        // console.log('(page-rendered)', e);
    }

    compareDraftable() {
        const fd = new FormData();
        fd.append('file1', this.leftFile, this.leftFile.name);
        this.http.post('localhost:8080/draftableDemo', fd)
            .subscribe(res => {
                console.log(res);
            });
    }

    upload() {
        const inputEl: HTMLInputElement = this.inputEl.nativeElement;
        const fileCount: number = inputEl.files.length;
        const formData = new FormData();
        if (fileCount > 0) { // a file was selected
            for (let i = 0; i < fileCount; i++) {
                formData.append('file[]', inputEl.files.item(i));
            }
            this.http
                .post('localhost:8080/draftableDemo', formData);
            // do whatever you do...
            // subscribe to observable to listen for response
        }
    }

1 个答案:

答案 0 :(得分:0)

  • 如何在Angular侧用代表键定义两个PDF?

当前,您已经有两个文件,您需要做的就是通过POST查询发送它们

let formData:FormData = new FormData();
formData.append('file1', this.pdfSrc1);
formData.append('file2', this.pdfSrc2);

const req = new HttpRequest('POST', 'localhost:8080/draftableDemo', formData);
  • 我是否需要更改API的期望值?

由于formData发送的PDF文件的键名与PostMan或正在等待的API完全相同,除非this.pdfSrc1 / this.pdfSrc2格式不正确,否则应该没问题

  • 我一直在阅读Angular文件上传器,每个人都在谈论哪个模块?

不需要角度文件上传器或标签