flutter 网络请求,上传文件,下载文件

1.开发环境Android studio 3.4.0
2.pubspec.yaml添加依赖如下:

  dio: ^3.0.0 # HTTP网络请求
  crypto: ^2.1.3 #加密 md5 sha1 HMAC(i.e. HMAC-MD5, HMAC-SHA1, HMAC-SHA256)等
  shared_preferences: ^0.5.0 # 添加sharedPreference依赖
  path_provider: ^1.6.5 #文件读写
  sqflite: ^1.3.0 #数据库存储
  permission_handler: ^4.1.0 #权限管理
  file_picker: ^1.4.3+2 #文件选择
  cached_network_image: ^2.0.0 #图片选择
  common_utils: ^1.1.3 # 精度

3.网络请求类

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'urls.dart';

class HttpReqUtil {
  Dio dio = null;

  HttpReqUtil._() {
    dio = new Dio();
    // 添加拦截器
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
      print("\n================== 请求数据 ==========================");
      print("url = ${options.uri.toString()}");
      print("headers = ${options.headers}");
      print("params = ${options.data}");
    }, onResponse: (Response response) {
      print("\n================== 响应数据 ==========================");
      print("code = ${response.statusCode}");
      print("data = ${response.data}");
      print("\n");
    }, onError: (DioError e) {
      print("\n================== 错误响应数据 ======================");
      print("type = ${e.type}");
      print("message = ${e.message}");
      print("stackTrace = ${e.error}");
      print("\n");
    }));
  }

  static HttpReqUtil dbUtils;

  static HttpReqUtil getInstance() {
    if (null == dbUtils) dbUtils = HttpReqUtil._();
    return dbUtils;
  }

  Future<Response> getData(String url) async {
    return await dio.get(url);
  }

  Future<Response> postForm(String url, Map<String, Object> params) async {
    var option = Options(
        method: "POST", contentType: "application/x-www-form-urlencoded");
    return await dio.post(url, data: params, options: option);
  }

  Future<Response> postJson(String url, Map<String, Object> params) async {
    var option = Options(method: "POST", contentType: "application/json");
    return await dio.post(url, data: params, options: option);
  }

  /**
   * 上传文件
   * 注:file是服务端接受的字段字段,如果接受字段不是这个需要修改
   */
  Future<Response> uploadFile(String filePath, String fileName) async {
    var postData = FormData.fromMap(
        {"file": await MultipartFile.fromFile(filePath, filename: fileName)});//file是服务端接受的字段字段,如果接受字段不是这个需要修改
    var option = Options(method: "POST", contentType: "multipart/form-data");//上传文件的content-type 表单
    return await dio.post(
      UPLOAD_FILE_N,
      data: postData,
      options: option,
      onSendProgress: (int sent, int total) {
        print("上传进度:" +
            NumUtil.getNumByValueDouble(sent / total * 100, 2)
                .toStringAsFixed(2) +
            "%"); //取精度,如:56.45%
      },
    );
  }

  /**
   * 下载文件
   */
  Future<Response> downloadFile(String resUrl, String savePath) async {
    //还好我之前写过服务端代码,不然我根本没有相对路劲的概念
    return await dio.download(resUrl, savePath,
        onReceiveProgress: (int loaded, int total) {
      print("下载进度:" +
          NumUtil.getNumByValueDouble(loaded / total * 100, 2)
              .toStringAsFixed(2) +
          "%"); //取精度,如:56.45%
    });
  }
}

4.调用方式:

login() async {
    var pwd = sha1.convert(utf8.encode("11111111"));
    HttpReqUtil.getInstance().postForm(LOGIN_N,
        {'username': '156564556', 'password': pwd, 'type': 3}).then((result) {
      print("返回数据:${result.toString()}");
    }).whenComplete(() {
      print("请求结束");
    }).catchError((err) {
      print("请求报错:" + err.toString());
    });
  }

  uploadFile() async {
  	//文件选择 [jpg]格式,可以设置更多,权限问题filepicker会帮你处理
    File file = await FilePicker.getFile(
        type: FileType.custom, allowedExtensions: ["jpg"]);
    print("上传图片地址:" + file.path);
    var fileName =
        file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
    HttpReqUtil.getInstance().uploadFile(file.path, fileName).then((result) {
      print("返回数据:${result.toString()}");
    }).whenComplete(() {
      print("请求结束");
    }).catchError((err) {
      print("请求报错:" + err.toString());
    });
  }

  downloadFile()async{
    var resUrl = 'http://static.maintenance.v3m2.ettda.com/files/fd/ec/2c/5ebb52dfca8ab0e479f15457/5ebb52dfca8ab0e479f15457.jpg';
    await getTemporaryDirectory().then((result){//获取临时存放路径
      HttpReqUtil.getInstance().downloadFile(resUrl, result.path+"/123.jpg");
    });
  }

5.实现效果
flutter 网络请求,上传文件,下载文件_第1张图片

你可能感兴趣的:(flutter)