条带读取文件同步的图像选择器路径 Flutter Web

image picker path for stripe readfilesync Flutter Web

我正在使用 file_picker flutter 包 https://pub.dev/packages/file_picker 我读过很多次,因为你不能在网络浏览器上访问路径,你需要使用字节属性,例如

FilePickerResult result = await FilePicker.platform.pickFiles();

if(result != null) {
   var path = print(result.files.single.path); // this will return null
   var bytes = print(result.files.singe.bytes); // this will return a Uint8List of bytes
} else {
   // User canceled the picker
}

但是我必须通过网络将我的用户 select 的图像从他们的设备上传到我的 Stripe Connect API,以便他们进行验证identity_document 他们注册的时候。字节 Uint8List 将从 firebase 抛出错误,这是我的代码:

export const uploadIdentityFront = async (uid: any, identityFront: any) => {
    
  const fp = fs.readFileSync(identityFront);
    
  const frontIdentity = await stripe.files.create({
        file: {
            data: fp,
            name: 'identityFront.jpg',
            type: 'application/octet-stream',
        },
        purpose: 'identity_document',
    });

    await updateId(uid, { frontIdentityFileId: frontIdentity.id })
    return frontIdentity;

}

抛出的错误:

[firebase_functions/unknown] TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received an instance of Array

为了做到这一点,我需要通过文件系统的 readFileSync 属性 发送图像文档,但是由于 Flutter Web 无法打印用户选择的图像的路径,我我一直在想如何解决这个问题

我使用此代码将字节发送到我的服务器,该服务器使用流发送。您可以使用 http 包发送流。

var request = http.MultipartRequest(
  'POST',
  Uri.parse('_url'),
);


request.files.add(
  http.MultipartFile.fromBytes(
    'identityFront', //name of field which you receive in api
    bytes, // bytes
    filename: 'identityFront.jpg', // optional name
    //contentType: content, optional media Type
 ));

 request.fields.addEntries([
     MapEntry('uid', 'uid_value_in_String_Type'),
 ]);
 
await request.send();

我终于解决了。对于任何试图通过 flutter web 将文件上传到 Stripe 的人,不要在后端服务器端代码中创建 fs.readFileSync。相反,删除它并上传这样的文件:

export const uploadIdentityFront = async (uid: any, identityFront: any) => {
        
  const frontIdentity = await stripe.files.create({
        file: {
            data: identityFront,
            name: 'identityFront.jpg',
            type: 'image/jpg',
        },
        purpose: 'identity_document',
    });

    await updateId(uid, { frontIdentityFileId: frontIdentity.id })
    return frontIdentity;

}

这样,您可以通过 file_picker 包上传文件并将其作为 picker.file.first.bytes 上传。但不要将其包装在字符串中 - 就像这样将其作为 firebase 函数中的可调用函数发送:

await uploadFrontPassport.call(
   <dynamic, dynamic>{'identityFront':picked.files.first.bytes}
);