天天看点

flutter阿里云OSS图片上传

一、选择图片:

使用插件 image_picker: “^0.5.0+3”

使用image_picker选择图片,代码如下:

// 相机拍照或者从图库选择图片
  pickImage(ctx) {
    // 如果已添加了1张图片,则提示不允许添加更多
    num size = fileList.length;
    if (size >= 1) {
      Scaffold.of(ctx).showSnackBar(new SnackBar(
        content: new Text("最多只能添加1张图片!"),
      ));
      return;
    }
    showModalBottomSheet<void>(context: context, builder: _bottomSheetBuilder);
  }
  _renderBottomMenuItem(title, ImageSource source) {
    var item = new Container(
      height: 60.0,
      child: new Center(child: new Text(title)),
    );
    return new InkWell(
      child: item,
      onTap: () async {
        Navigator.of(context).pop();
        setState(() {
          _imageFile = ImagePicker.pickImage(source: source);
        });
      },
    );
  }
  Widget _bottomSheetBuilder(BuildContext context) {
    return new Container(
        height: 182.0,
        child: new Padding(
          padding: const EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 30.0),
          child: new Column(
            children: <Widget>[
              _renderBottomMenuItem("相机拍照", ImageSource.camera),
              new Divider(
                height: 2.0,
              ),
              _renderBottomMenuItem("图库选择照片", ImageSource.gallery)
            ],
          ),
        ));
  }
           

选择图片后回调,代码如下

List<File> fileList = new List();
Future<File> _imageFile;
 
Widget build(BuildContext context) {
    return new Scaffold(
      body: new FutureBuilder(
        future: _imageFile,
        builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
          if (snapshot.connectionState == ConnectionState.done && snapshot.data != null && _imageFile != null) {
            // 选择了图片(拍照或图库选择),添加到List中
            fileList.add(snapshot.data);
            // 阿里云OSS上传图片
            uploadImage(snapshot.data);
            _imageFile = null;
          }
          // 返回的widget
          return listView();
        },
      ),
    );
  }
           

二、上传图片

使用插件dio: “^2.0.0”

使用dio网络访问框架进行上传,代码如下

//上传图片
  uploadImage(File file) {
    //签名
    String url = Constants.BASE_URL + "/ossSignature";
    print("ossSignatureUrl: $url");
    NetUtils.get(url).then((obj) async {
      if (obj != null) {
        if (obj['code'] == 0) {
          var _sign = obj['data'];
          //创建dio对象
          Dio dio = new Dio();
          //dio的请求配置
          dio.options.responseType = ResponseType.plain;
          dio.options.contentType = ContentType.parse("multipart/form-data");
          //文件名
          String path = file.path;
          String chuo = DateTime.now().millisecondsSinceEpoch.toString() + path.substring(path.lastIndexOf('.'));
          String fileName = path.lastIndexOf('/') > -1 ? path.substring(path.lastIndexOf('/') + 1) : path;
          //创建一个FormData,作为dio的参数
          FormData formData = new FormData.from({
            'chunk': '0',
            'OSSAccessKeyId': _sign['accessid'].toString(),
            'policy': _sign['policy'].toString(),
            'Signature': _sign['signature'].toString(),
            'Expires': _sign['expire'].toString(),
            'key': _sign['dir'] + chuo,
            'success_action_status': '200',
            'Access-Control-Allow-Origin': '*',
            'file': new UploadFileInfo(new File(path), fileName)
          });
          try {
            Response response = await dio.post(_sign['host'], data: formData);
            if (response.statusCode == 200) {
              setState(() {
                imgUrl = _sign['host'] + '/' + _sign['dir'] + chuo;
              });
            } else {
              Toast.show(context, '图片上传失败');
            }
          } on DioError catch (e) {
            Toast.show(context, '上传失败');
            print("get uploadImage error: $e");
          }
        }
      }
    }).catchError((e) {
      print("get uploadImage error: $e");
    });
  }