ionic-framework - 如何使用 http.post 上传文件和表单数据

标签 ionic-framework ionic2 angular2-forms angular-file-upload

我正在提交一个表单,其中包含 title 之类的字段和 description使用 http.post它工作正常。我还允许用户使用相机拍摄照片并将其保存为 base64 中的字符串。格式。我需要通过相同的 POST 请求将这张照片提交给服务器。我怎样才能做到这一点?到目前为止,我的代码如下,服务器在名为“photo”的字段中查找上传的照片:

headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'});
options = new RequestOptions({ headers: this.headers });

let data = {
  title: item.title,
  description: item.description
};

let params = new URLSearchParams();
for(let key in data){
    params.set(key, data[key]) 
}

this.http.post('http://example.com/items', params.toString(), this.options).subscribe(
  (result) => {
    console.log("success!");
  },
  (err) => {
    console.log(JSON.stringify(err));
  }
);

最佳答案

您必须使用文件传输插件来上传文件。我建议使用文件而不是 base64。当以高分辨率捕获图像时,Base64 是非常大的字符串。

html

<button (click)="takePicture()">Take a picture</button>

ts
takePicture()
{
    const options: CameraOptions = {
        quality: 100,
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE
    }
    this.camera.getPicture(options).then((imageData) => {
        this.allImageData = imageData;
        var data = {
            "imgUrl": this.allImageData,
            "challenge_id": this.challenges_id
        }
        let uploadImageModal = this.modalCtrl.create(UploadBodyImagePage,{ data: data });
        uploadImageModal.present();
        uploadImageModal.onDidDismiss(data => {
            this.viewCtrl.dismiss();
        });
    }, (err) => 
    {
        // alert("error");
    }

    );
}

您可以使用以下功能将数据发送到服务器
uploadData()
{
    this.disabledButton = true;
    this.commonProvider.retrieve('userData').then(res=>{ 

        const fileTransfer: TransferObject = this.transfer.create();
        var options = {
            fileKey: "file",
            fileName: "filename",
            chunkedMode: false,
            mimeType: "multipart/form-data",
            params : {
                "methodName": "saveBodyUpdate",
                "challenge_id": this.challenge_id,
                "userId": res['user_id'],
                "loginToken": res['loginToken'],
                "days_id":"1",
                "weight": this.myweight
            }
        };  
        fileTransfer.onProgress((e)=>
        {
            this.prg=(e.lengthComputable) ?  Math.round((e.loaded * 100) / e.total) : -1; 
            this.changeDetectorRef.detectChanges();
        });
        fileTransfer.upload(this.imgSrcData, this.apiUrl, options).then((res) => 
        {   
            console.log(JSON.stringify(res));
            this.viewCtrl.dismiss();
        },(err)=> {
            this.viewCtrl.dismiss();
        });
    })  
}

关于ionic-framework - 如何使用 http.post 上传文件和表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46439618/

相关文章:

angularjs - 使用 ng-repeat 时无法居中对齐文本

json - ionic2 属性在类型 '{}' 上不存在

typescript - TypeError : v. context.$implicit 不是函数

sqlite - ionic 2 错误 'ReferenceError: sqlitePlugin is not defined'

Angular2 - 带有表单的模态

javascript - 没有错误时什么也没有显示。代码运行良好

angularjs - ngOnInit 和 Constructor 被调用两次

javascript - 如何在 Ion Modal 中从调用页面获取数据

angular - 添加/删除响应式(Reactive)表单验证器以动态创建输入

angular - 如何在 ANGULAR 2 中提交表单时重置表单验证