飞镖:将.jpg文件上传到Google云端硬盘 [英] Dart: upload .jpg file to google Drive

查看:86
本文介绍了飞镖:将.jpg文件上传到Google云端硬盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将.jpg文件上传到Dart中的Google云端硬盘:

I try to upload a .jpg file to google Drive in Dart:

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帖子上传到Google云端硬盘

I get a status code bad request: 400 I saw the post about the same isue: Dart: http post upload to google Drive

我想念什么?
谢谢

What am I missing? Thanks

推荐答案

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

Maybe you could use the googleapis package. It could be simpler to use.

将此依赖项添加到 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()));
}

这篇关于飞镖:将.jpg文件上传到Google云端硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆