【问题标题】:Cordova - How to POST (upload to server) image picked with ImagePicker?Cordova - 如何使用 ImagePicker 发布(上传到服务器)图像?
【发布时间】:2017-02-27 03:56:24
【问题描述】:

我使用 Cordova ImagePicker 插件从手机图库中挑选图像。它返回图像文件 URI。如何根据其 URI 路径将该图像发送到服务器?

pickImage() {
    ImagePicker.getPictures({maximumImagesCount: 1}).then(
        results => {
            results.map(file_uri => {
                console.log('GOT FILE URI: ' + file_uri);
                // SEND FILE TO SERVER
            });
        }, err => {
        }
    );
}

尝试但失败:

  • 文件传输插件。它应该根据本地 URI 路径将图像上传到端点。但它对我不起作用,并且默默地失败了。
  • 文件插件。它应该能够读取本地文件并返回二进制文件,然后我可以将其 POST 到服务器。但它不读取文件并且对我来说默默地失败了。

【问题讨论】:

    标签: cordova ionic-framework cordova-plugins


    【解决方案1】:

    Base64 插件似乎工作正常。它从图像 URI 路径中获取 base64 字符串,然后可以将其 POST 到服务器。

    示例客户端代码 - JavaScript (ES6):

    pickImage() {
        ImagePicker.getPictures({maximumImagesCount: 1}).then(
            results => {
                results.map(file_uri => {
                    console.log('GOT FILE URI: ' + file_uri);
                    window.plugins.Base64.encodeFile(file_uri, base64 => {
                        // POST base64 string to server;
                    }, error => {
                        console.error(error);
                    });
                });
            }, error => {
                console.error(error);
            }
        );
    }
    

    示例服务器代码在 POST 处理程序 - Python:

    import base64
    ...
    def post(self, filename):
        b64string = self.request.body.decode()
        b64data = b64string.split(',')[1]
        binary = base64.b64decode(b64data)
        with open('/path/to/images/' + filename, 'wb') as f:
            f.write(binary)
    

    额外 - 如果你需要获取二进制文件,只需要使用 File API,你可以像这样创建一个 Blob (source):

    base64toBlob(base64string) {
        var byteString = atob(base64string.split(',')[1]);
        var mimeString = base64string.split(',')[0].split(':')[1].split(';')[0]
        var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        var bb = new Blob([ab], {type: 'image/jpeg'}); // your mime type here
        return bb;
    }
    

    【讨论】:

      【解决方案2】:

      你可以简单地使用 outputType: 1

              let options = {
              maximumImagesCount: 8,
              quality: 100,
              outputType: 1
          }
          ImagePicker.getPictures(options).then((results) => {
              for (var i = 0; i < results.length; i++) {
                  this.uploadImage(results[i]);
              }
          }, (err) => {
              console.log(JSON.stringify(err));
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-15
        • 1970-01-01
        • 2023-03-13
        • 2014-09-01
        • 1970-01-01
        • 2018-08-24
        • 2021-01-18
        • 1970-01-01
        相关资源
        最近更新 更多