dart - 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
我错过了什么?谢谢
解决方案
也许你可以使用这个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()));
}
推荐阅读
- java - 如何使用插件依赖项和 java 模块系统修复 exec-maven-plugin?
- javascript - Vuelidate sameAs 无法读取组件的数据
- kubernetes - nodeAffinity & nodeAntiAffinity 被忽略
- visual-studio - Visual Studio 内存不足,只有 500mb 和 23gb 可用
- html - 在 R 中登录的网页抓取页面
- javascript - 如何使用画布和 javascript 在图表中绘制填充弧?
- java - 我将如何在 1.16.5 的 forge 中制作自定义镐?
- amazon-web-services - “无法刷新令牌:缺少必需的参数身份验证参数。” - AWS Amplify 拉取 API
- microsoft-information-protection - Microsoft 信息保护 SDK 损坏 PDF
- python - 模块请求不想安装