繁体   English   中英

如何在 nativescript-angular 中为图像做 http post

[英]How to do http post for image in nativescript-angular

所以我试图将用户图库中的图像上传到我的 API。 目前,我可以从图库中选择图像,但它不允许我将所选图像传递到另一个函数以将其发送到 API。 API没有问题,已经过测试。 我正在使用“nativescript-imagepicker”插件

这是代码:

  getImage() {
        let context = imagepicker.create({
            mode: "single" // use "multiple" for multiple selection
        });

    context
        .authorize()
        .then(function () {
            return context.present();
        })
        .then(function (selection) {
                selection.forEach(function (selected) {
                console.log(selected)
                this.uploadImage(selected)
            });
        })
        .catch(function (e) {
            console.log('error')
            // process error
        });
}

uploadImage(imageAsset) {

    console.log('uploading image')

    let token = JSON.parse(appSettings.getString('token'));
    let options = new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded",
        // "Content-Type": "application/octet-stream",
        "Authorization": "Bearer " + token
    });
    let userId = appSettings.getString('currentUserId')
    let url = 'http://localhost:5000/api/users/' + userId + '/photos'
    console.log(url)
    this.http.post(url, imageAsset, { headers: options }).subscribe(res => {
        console.log(res)
        console.log('Success')
    }, error => {
        console.log('Failed');
    });
}

它运行 getImage 函数并将我带到画廊,然后一旦选择了图像,它就会运行 console.log 函数(它可以正常工作,因此我相信正在接收图像并记录图像的路径)。 这是 console.log 的输出

{
JS:   "_observers": {},
JS:   "_options": {
JS:     "keepAspectRatio": true,
JS:     "autoScaleFactor": true
JS:   },
JS:   "_android": "/storage/emulated/0/DCIM/Camera/IMG_20200211_200350.jpg"
JS: }

但是,它不会对图像运行“this.uploadImage”函数,因此它会跳过此操作并转到“.catch”块并记录“错误”。 它还在控制台中记录了这一点

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'uploadImage' of undefined
JS: TypeError: Cannot read property 'uploadImage' of undefined
JS:     at file:///src\app\_mocks\test\test.component.ts:38:25
JS:     at Array.forEach (<anonymous>)
JS:     at file:///src\app\_mocks\test\test.component.ts:36:30
JS:     at ZoneDelegate.push.../node_modules/nativescript-angular/zone-js/dist/zone-nativescript.js.ZoneDelegate.invoke (file:///node_modules\nativescript-angular\zone-js\dist\zone-nativescript.js:388:0)
JS:     at Object.onInvoke (file:///node_modules\@angular\core\fesm5\core.js:26256:0)
JS:     at ZoneDelegate.push.../node_modules/nativescript-angular/zone-js/dist/zone-nativescript.js.ZoneDelegate.invoke (file:///node_modules\nativescript-angular\zone-js\dist\zone-nativescript.js:387:0)
JS:     at Zone.push.../node_modules/nativescript-angular/zone-js/dist/zone-nativescript.js.Zone.run (file:///data/d...

进口

import * as fs from "tns-core-modules/file-system";
import * as camera from "nativescript-camera";

职能

    // This method allows the user to take a picture, save to the gallery, display it on the screen, convert it to base64 and then send it to the API   
  1. 拍照,保存到图库,另存为base64字符串,显示在屏幕上

    takePicture() { const options = { width: 300, height: 300, keepAspectRatio: false, saveToGallery: true }; camera.takePicture(options). then((imageAsset) => { console.log("Size: " + imageAsset.options.width + "x" + imageAsset.options.height); console.log("keepAspectRatio: " + imageAsset.options.keepAspectRatio); console.log("Photo saved in Photos/Gallery for Android or in Camera Roll for iOS"); const imgPhoto = new ImageSource(); const that = this; imgPhoto.fromAsset(imageAsset).then((imgSrc) => { if (imgSrc) { // This is the base64 string, I saved it to a global variable to be used later that.bstring = imgSrc.toBase64String("jpg"); console.log(that.bstring); // This bit saves it as an 'Image' to the app const mil = new Date().getTime(); const folder = fs.knownFolders.documents(); const path = fs.path.join(folder.path, `SaveImage${mil}`); const saved = imgPhoto.saveToFile(path, "png"); // This saves the image to the global variable which will be used to display it on the screen that.saveImage = path; that.picHeight = imgSrc.height; } else { alert("Image source is bad."); } }); }).catch((err) => { console.log("Error -> " + err.message); }); }
  2. 将其发送到 API

     // This is just a generic API call that uses the base64 string as the image // you can choose whether to call the function and pass the image into it, or just use the one saved in the global variable uploadImage(image = null) { const imageString; if (image) { let imageString = image } else { imageString = this.b64image } // This is where you create the object to be sent up to the API, in this example I'm sending up a description aswell, so I've added the property here const data = { B64String: imageString, Description: this.imageDescription }; // This is where i create my headers, in this case I'm using authorization const headers = new HttpHeaders({ Authorization: "Bearer " + appSettings.getString("tok") }); // This is my API call this.http.post(this.baseUrl + "users/" + this.userId + "/photos", data, { headers}) .subscribe((res) => { console.log(res) }, (error) => { console.log(error) } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM