美文网首页
Flutter 图片上传

Flutter 图片上传

作者: 小王在努力 | 来源:发表于2020-11-11 09:43 被阅读0次

1、导入相关的库

dio: ^3.0.9
image_picker: ^0.6.7+14

2、代码的实现

//上传图片demo
static Future<String> uploadTask() async{
  //上传域名
  final url = "xxx";
  //上传携带参数
  var map = new Map<String, dynamic>();
  String time = appTime.timeStamp();
  String auto = "key" + time;
  map.addAll({"uuid":"807D845D-0787-43B4-B797-139EB305E756"});
  map.addAll({"from":"6"});
  map.addAll({"time":time});
  map.addAll({"auth_key":Md5.md5String(auto)});
  print(map);
  //上传文件
  var image = await ImagePicker.pickImage(source: ImageSource.gallery);
  final path = image.path;
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  print(name);
  print(path);
  FormData formData = new FormData.fromMap({
    "name" :"image",//文件名
    "fileName" :"image.jpeg",
    "mimeType" :"image/jpeg",
    "image": await MultipartFile.fromFile(path, filename:name),
  });

  Dio dio = new Dio();
  BaseOptions options = BaseOptions();
  options.connectTimeout = 10 * 1000;
  options.receiveTimeout = 20 * 1000;
  dio.options = options;
  Response response = await dio.post(url,data:formData,queryParameters:map,onSendProgress: (int count, int total) {
    print('-----------${count / total}-------------'); //上传进度
  });
  var code = response.statusCode;
  return await response.data.toString();
}

注意
a、name:是服务端视频定义的、比如服务端定义是file = xxxx.jpeg ,那么这里name就改为file
b、fileName:图片是image.jpeg,视频则是video.mp4
c、mimeType:图片是image/jpeg,视频则是video/mp4
d、4个参数:from time uuid auth_key

相关文章

网友评论

      本文标题:Flutter 图片上传

      本文链接:https://www.haomeiwen.com/subject/rkojbktx.html