0

我需要将图像作为“文件”发送到我的服务器,但我不知道该怎么做。我正在使用 nativescript-camera-plus 和 nativescript-background-http 插件来发送请求。这是代码。

                          onTakePictureTap() {
    requestPermissions().then(
        () => {
            takePicture({ width: this.width, height: this.height, keepAspectRatio: this.keepAspectRatio, saveToGallery: this.saveToGallery, allowsEditing: this.allowsEditing })
                .then((imageAsset: any) => {
                    this.cameraImage = imageAsset;
                    let that = this;
                    imageAsset.getImageAsync(function (nativeImage, ex) {
                        if (ex instanceof Error) {
                            throw ex;
                        } else if (typeof ex === "string") {
                            throw new Error(ex);
                        }

                        let imgPhoto = new ImageSource();

                        imgPhoto.fromAsset(imageAsset).then((imgSrc) => {

这是我设置 nativescript-background-http 的地方

                            var bghttp = require("nativescript-background-http");
                            var session = bghttp.session("image-upload");
                            let token = JSON.parse(appSettings.getString('token'));

这是请求

                            var request = {
                                url: environment.apiUrl + 'users/1/photos',
                                method: "POST",
                                headers: {
                                    "Content-Type": "form-data/File",
                                    "Authorization": "Bearer " + token
                                },
                                description: "Uploading "
                            };

这是任务,我发送图像和请求

                            var task = session.uploadFile(imgSrc, request);

                            task()

                        },
                            err => {
                                console.log('Error getting image source: ');
                                console.error(err);
                                alert('Error getting image source from asset');
                            });
                    });
                }, (error) => {
                    console.log("Error: " + error);
                });
        },
        () => alert('permissions rejected')
    );
}

我认为问题在于它是作为 ImageAsset 而不是“文件”发送的(但我不确定)。我认为我不需要更改文件类型,我只需要让它知道这是一个“文件”,就像我在邮递员中所做的那样

这就是它在邮递员中的样子(这有效)

图片

4

2 回答 2

0

没错,至少在 iOS 图像资产不是文件。它只包含对 PHAsset 的引用。

此外,您似乎正在将图像源直接传递给插件。它应该是文件路径。您必须将图像写入本地文件夹,然后使用文件路径。使用saveToFile(...)ImageSource 实例上的方法,然后将文件路径传递给后台 http 插件。

imgSrc.saveToFile(filePath, imageFormat)

于 2020-03-15T17:10:44.337 回答
0

这是一个最小的解决方案:

document.getElementById('file').addEventListener('change', function () {
  fetch('https://api.imgur.com/3/upload', { method: 'POST', body: document.getElementById('file').files[0] });
});
<input id="file" type="file">

由于CORS ,该代码在 StackOverflow 代码段中不起作用,但您明白了

于 2020-03-15T10:36:21.373 回答