로메오의 블로그

[IONIC] 파일 업로드 - to Spring 본문

Frontend/angular

[IONIC] 파일 업로드 - to Spring

romeoh 2020. 5. 29. 14:00
반응형

ionic 차례

 

UtilService.ts

import { TaskService } from 'src/app/services/task.service';


export class UtilService {

    constructor(public toastController: ToastController,
        private taskService: TaskService
    ) { }
    
    /**
     * PDF 파일을 업로드 한다.
     * filePath: file:///var/mobile/Containers/Data/Application/3A918EF3-8093-4857-A9B3-B49DA0D820CC/Documents/20200527105850.pdf
     */
    uploadPdfFile(filePath: string) {
        const that = this
        window['resolveLocalFileSystemURL'](filePath, fileEntry => {
            fileEntry['file'](file => {
                var reader = new FileReader()
                reader.onloadend = function (encodedFile) {
                    const base64Pdf = encodedFile.target['_result']
                    const file = that.dataURIToBlob(base64Pdf)
                    
                    let formData = new FormData();
                    formData.append('files[0]', file, 'file.pdf');

                    let uploadOptions = new FileUploadOption()
                    uploadOptions.title = 'title'
                    
                    that.taskService.uploadPdf(formData, uploadOptions)
                };
                reader.readAsDataURL(file)
            })
        })
    }
    
    /**
     * base64를 Blob으로 변환한다.
     */
    dataURIToBlob(dataURI: string) {
        const splitDataURI = dataURI.split(',')
        const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
        const mimeString = splitDataURI[0].split(':')[1].split(';')[0]
        const ia = new Uint8Array(byteString.length)

        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i)
        }

        return new Blob([ia], { type: mimeString })
    }
 }   
 
 /**
 * Interface 객체
 */
 export class FileUploadOption {
 title: string;
 }

 

task.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class ReceiptService {

    constructor(
        private httpClient: HttpClient,
        private authService: AuthenticationService
    ) { }

    /**
     * PDF 파일 업로드
     */
    uploadPdf(formData: FormData, uploadOption: FileUploadOption) {
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type':  'multipart/form-data',
                'Accept': 'application/json'
            })
        };
		
        return this.httpClient.post<any[]>(
            'http://domain.com/task.do',
            formData,
            httpOptions
        ).toPromise();
    }
}

 

 

TaskController.java

@RestController
@CrossOrigin(exposedHeaders="X-....")
public class TaskController {
	
    @RequestMapping('task.do')
    public List<FtpFile> uploadPdf(MultipartHttpServletRequest request) {
    	....
        return rtnList;
    }
}

 

 

 

크롬디버깅 

 

 

 

 

ionic 차례

반응형

'Frontend > angular' 카테고리의 다른 글

[IONIC] IONIC에서 Cordova Plugin 사용하기  (0) 2020.06.04
[IONIC] navigation 파라미터 넘기기  (0) 2020.05.26
[IONIC] Document Scanner  (0) 2020.05.14
[IONIC] Firebase Firestore 연결  (0) 2020.02.13
[IONIC] Firebase Login  (1) 2020.02.12
Comments