首页 > 解决方案 > Dart:将 .jpg 文件上传到谷歌云端硬盘

问题描述

我尝试将 .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

我错过了什么?谢谢

标签: dartupload

解决方案


也许你可以使用这个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()));
}

推荐阅读