在使用命令行curl命令成功上传文件后,我尝试将文件上传到Dart中的Google云端硬盘:
curl -X POST -L \
-H "Authorization: Bearer $access_token" \
-F "metadata={name : 'test_send_file.zip'};type=application/json;charset=UTF-8" \
-F "file=@test_send_file.zip;type=application/zip" \
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"
飞镖版本:
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
final access_token = "....";
main() async {
File first = File('test_send_file.zip');
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 : test_send_file.zip};type=application/json;charset=UTF-8";
request.files.add(await http.MultipartFile.fromPath('test_send_file.zip', first.path,
contentType: new MediaType('application', 'zip')));
print("request.toString: " + request.toString());
http.StreamedResponse response = await request.send();
print(response.statusCode);
}
我收到状态代码错误请求:400
有人可以帮助我在Dart中向Google驱动器发送文件http请求吗?
答案 0 :(得分:1)
要将更复杂的表单项添加到MultipartRequest
时,可以将其添加为文件。 (是的,有点奇怪...)
将request.fields.add...
替换为...
request.files.add(http.MultipartFile.fromString(
'metadata',
json.encode({'name': 'test_send_file.zip'}),
contentType: MediaType('application', 'json'),
));