【问题标题】:Dart: upload .jpg file to google DriveDart:将 .jpg 文件上传到谷歌云端硬盘
【发布时间】:2019-05-09 13:21:38
【问题描述】:

我尝试将 .jpg 文件上传到 Dart 中的 google Drive:

final access_token = '...';

// sfilePath is "/storage/emulated/0/test/"
// sfileName is "test"

Uri uri = Uri.parse('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');

http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.headers["Authorization"] = "Bearer $access_token";
request.fields['metadata'] =  "{name : " + sfileName + '.jpg' +  "};type=application/json;charset=UTF-8";
request.files.add(http.MultipartFile.fromString('metadata',
                                  JSON.jsonEncode({'name': sfilePath + sfileName + '.jpg'}),
                                  contentType: MediaType('application', 'json'),
                  ));

http.StreamedResponse response = await request.send();
print('>>>>>>>>>>>>>>>>>>>>>' + response.statusCode.toString());

我收到一个状态码错误请求:400 我看到了关于同样问题的帖子: Dart: http post upload to google Drive

我错过了什么? 谢谢

【问题讨论】:

    标签: dart upload


    【解决方案1】:

    也许您可以使用googleapis 包。使用起来可能更简单。

    在你的pubspec.yaml中添加这个依赖

    dependencies:
      googleapis:
      googleapis_auth:
    

    并使用googleapis 库:

    import 'package:googleapis/drive/v3.dart';
    import 'package:googleapis_auth/auth_io.dart';
    import 'dart:io' as io;
    
    main() async {
      AuthClient client = await clientViaServiceAccount(
          ServiceAccountCredentials.fromJson({/* here the credentials */}),
          ['https://www.googleapis.com/auth/drive']);
    
      var driveApi = DriveApi(client);
    
      var fileToUpload = io.File('my_file.png');
    
      await driveApi.files.create(File()..name = 'my_file.png',
          uploadMedia: Media(fileToUpload.openRead(), fileToUpload.lengthSync()));
    }
    

    【讨论】:

    • 我遇到的大部分上传代码都是这样的。有没有办法实际获取上传进度?
    • @Xavier 有没有办法上传到特定文件夹?喜欢指定文件夹名称,如果存在则将文件上传到它,如果不创建它并将文件上传到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    相关资源
    最近更新 更多