Flutter-阿里云OSS基于POST上传文件

Flutter开发都两年了。最新需求通过OSS基于POST上传文件。
直接上代码:

  //获取上传Token
  void _uploadImgToosm(File imagFile) async {
  //第一步每次上传之前请求oss_token来获取上传必须参数。
    var imgFileName = imagFile.path.split("/")[imagFile.path.split("/").length - 1];
    Map<String, String> header = new Map();
    Map<String, String> parames = new Map();
    parames["fileName"] = imgFileName; //
    parames["fileType"] = "image";
    String jsons = json.encode(parames);
    MyNetUtil.instance.postData("/mjs/api/v1/platform/oss_token", (value) async {
      InformationBeanEntity informationBeanData = InformationBeanEntity().fromJson(value);
      Dio dio = new Dio();
      dio.options.responseType = ResponseType.plain;
      dio.options.contentType ="multipart/form-data";
      String host = informationBeanData.data.host;
      var imgFileName = imagFile.path.split("/")[imagFile.path.split("/").length - 1];
      Map<String, dynamic> map = new Map();
      map["Filename"] = imgFileName;
      map["key"] = informationBeanData.data.key;
      map["policy"] = informationBeanData.data.policy; //"$host/$imgFileName.$ext";
      map["OSSAccessKeyId"] = informationBeanData.data.accessKeyId;
      map["success_action_status"] = "200";
      map["signature"] = informationBeanData.data.signature;
      map["Access-Control-Allow-Origin"]="*";
      map["file"] = await MultipartFile.fromFile(imagFile.path, filename: imgFileName);
      FormData formDatas = new FormData.fromMap(map);
      Options baseOptions = Options(
        method: "post",
        contentType:"multipart/form-data",
        receiveTimeout: 5000,
        followRedirects: true,
      );
      try{
        await new Dio().post(host, data: formDatas,options:baseOptions).then((value){
          print("上传成功: $value");
          if(value.statusCode==200){//表示上传成功了。
            //这个就是我们上传之后的图片地址。通过这个imgUrl来访问下载图片
           String imgUrl = host+ '/' +informationBeanData.data.key;
           updateAvatar(imgUrl);
          }
        });
      }catch(e){
        print(e.toString());
      }

    }, headers: header, formart: jsons);
  }

代码太丑自己封装一下吧。作为一个记录

猜你喜欢

转载自blog.csdn.net/m0_37667770/article/details/106220222