You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter应用直传JSON数据至AWS S3存储桶方案求助

解决方案步骤

1. S3存储桶基础配置

  • 配置CORS规则,允许Flutter应用发起文件上传请求(生产环境建议限制域名,而非通配符):
    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    </CORSConfiguration>
    
  • 创建IAM用户,分配最小权限的S3上传策略(仅允许写入目标存储桶),保存该用户的Access Key和Secret Key。

2. Flutter端上传JSON文件到S3

方式一:原生HTTP请求(无第三方依赖冗余)

先将JSON数据写入本地临时文件,再通过AWS SigV4签名上传:

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'package:aws_signature_v4/aws_signature_v4.dart';

// 将JSON数据转为本地文件
Future<File> generateJsonFile(Map<String, dynamic> jsonData) async {
  final tempDir = await getTemporaryDirectory();
  final jsonFile = File('${tempDir.path}/upload_data.json');
  await jsonFile.writeAsString(jsonEncode(jsonData));
  return jsonFile;
}

// 签名并上传到S3
Future<void> uploadJsonToS3(File file, String bucketName, String accessKey, String secretKey) async {
  final signer = AWSSigV4Signer(
    credentials: AWSClientCredentials(accessKey: accessKey, secretKey: secretKey),
  );

  final putRequest = http.MultipartRequest(
    'PUT',
    Uri.parse('https://$bucketName.s3.amazonaws.com/${file.path.split('/').last}'),
  );
  putRequest.files.add(await http.MultipartFile.fromPath('file', file.path));

  final signedRequest = await signer.sign(
    putRequest,
    serviceName: 's3',
    region: 'us-east-1', // 替换为你的存储桶区域
  );

  final response = await http.Response.fromStream(await signedRequest.send());
  if (response.statusCode == 200) {
    print('JSON文件上传成功');
  } else {
    print('上传失败: ${response.body}');
  }
}

方式二:AWS Amplify简化实现

确保已初始化Amplify Storage模块,然后直接调用上传API:

import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_storage_s3/amplify_storage_s3.dart';

Future<void> uploadWithAmplify(File jsonFile) async {
  try {
    await Amplify.Storage.uploadFile(
      local: jsonFile,
      key: 'uploaded_data.json',
      options: const StorageUploadFileOptions(
        accessLevel: StorageAccessLevel.protected,
      ),
    );
    print('Amplify上传完成');
  } on StorageException catch (e) {
    print('Amplify上传错误: ${e.message}');
  }
}

3. 配置S3触发Lambda函数

  • 进入Lambda控制台,给目标函数添加S3触发器:选择你的存储桶,触发事件勾选Put(仅文件上传时触发),设置后缀过滤为.json(仅处理JSON文件)。
  • 给Lambda执行角色添加S3读取权限:附加AmazonS3ReadOnlyAccess策略,或自定义策略仅允许读取目标存储桶。

4. Lambda处理S3中的JSON文件

以下是Node.js示例,读取S3文件并处理:

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

exports.handler = async (event) => {
  // 解析S3事件中的文件信息
  const s3Record = event.Records[0].s3;
  const bucketName = s3Record.bucket.name;
  const fileKey = decodeURIComponent(s3Record.object.key.replace(/\+/g, ' '));

  // 读取S3中的JSON文件
  const fileData = await s3.getObject({ Bucket: bucketName, Key: fileKey }).promise();
  const jsonContent = JSON.parse(fileData.Body.toString());

  // 这里添加你的业务处理逻辑
  console.log('待处理的JSON数据:', jsonContent);

  return {
    statusCode: 200,
    body: JSON.stringify('JSON文件处理完成')
  };
};

内容的提问来源于stack exchange,提问作者Saurabh Kulkarni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:55:16