输入类型=文件和Spring Boot的Angular 2模板形式 [英] Angular 2 template form with input type=file and spring boot

查看:84
本文介绍了输入类型=文件和Spring Boot的Angular 2模板形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个输入的表单:一个输入文本,另一个输入文件. 如何将文件传递到后端Spring Boot?以及如何使用postgresql数据库存储或获取那里的内容数据. 预先感谢您的退货.

I have a form with two inputs: one type text and the other is file. how can i pass the file to backend spring boot? and how to store it or get there content data with postgresql database. thank you in advance for return.

推荐答案

HTML文件

<input #csvFile accept=".csv" #file (change)="onCSVFileSelect(file.files)" type="file">

TypeScript文件组件类

@ViewChild('csvFile') csvFile: any;

//On File Select
onCSVFileSelect(files) {
    let file: File = files[0];

    if (file.type == "text/csv") {

        this.selectedFileName = file.name;
        this.customerService.uploadCustomerFile(file).subscribe((fileUploadResponse) => {
           //Success Block
        }, (error) => {
           //Error Block
        });
    } else {
        //alert("Plase select .csv file");
        this.reset();
    }
}

TypeScript文件服务类

uploadCustomerFile(access_token: string, file: File): Observable<any> {

        let headers = new Headers();

        let options = new RequestOptions({ headers: headers }); 

        let formData = new FormData();
        formData.append('customerData', file);       

        return this.http.post(this.baseUrl + "getCustomerCSVFile", formData, options)
                .map((res: Response) => res.json() || {});
}

Spring Controller

@RequestMapping(value = "/getCustomerCSVFile", method = RequestMethod.POST)
public ResponseGenerator getCustomerCSVFile(@RequestParam MultipartFile customerData) {
        ResponseGenerator responseGenerator = new ResponseGenerator();
        try {

            if (customerData != null) {
                System.out.println(customerData.getOriginalFilename());
            }
            return responseGenerator;
        } catch (Exception e) {
            logger.error("Error while updating user : ", e);
            return responseGenerator;
        }
}

这篇关于输入类型=文件和Spring Boot的Angular 2模板形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆