Flutter解决图片File格式上传失败,通过dio上传文件(图片)

上传请求方法如下:

Future uploadRequest(url,{map}) async{
  try{
    Response response;
    Map<String, dynamic> headers = new Map();
    SharedPreferences sp = await SharedPreferences.getInstance();
    String cookie = sp.get("cookie");
    if(cookie==null || cookie.length==0){
    }else{
      headers['Cookie'] = cookie;
    }
    Options options = Options(
        headers: headers
    );

    FormData formData;
    formData = FormData.from(map);
    Dio dio = new Dio();
    if(map == null){
      response = await dio.post<String>(url);
    }else{
      response = await dio.post<String>(url,data: formData,options: options);
    }
    print("POST:URL="+url);
    print("POST:StatusCode="+response.statusCode.toString());
    print("POST:BODY="+formData.toString());
    print("POST:RESULT="+response.data.toString());
    if(response.statusCode == 200){
      return response.data;
    }else{
      return REQUEST_ERROR;
    }
  }catch(e){
    print(REQUEST_ERROR+"\nPOST:URL="+url);
    print(REQUEST_ERROR+"\nPOST:BODY="+map.toString());
    print(REQUEST_ERROR+"\nPOST:ERROR="+e.toString());
    return REQUEST_ERROR;
  }
}

dio2.0+使用方法:

1.获取文件名及格式

String path1 = _image1.path;
var name1 = path1.substring(path1.lastIndexOf("/") + 1, path1.length);
String suffix1 = name1.substring(name1.lastIndexOf(".") + 1, name1.length);

2.调用上传方法(参数转化很重要)

var data = {
 'loadingFile': UploadFileInfo(new File(path1), name1,
          contentType: ContentType.parse("image/$suffix1")
          ),//图片1
}
 uploadRequest(HttpApi.PAY_ORDER, map: data).then((val) {
      print("支付=" + val.toString());
  }

dio3.0+使用方法:

///上传商品banner
  static Future fetchUploadProductBanner(String path) async{
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var image = await MultipartFile.fromFile(
      path,
      filename: name,
    );
    FormData formData = FormData.fromMap({
      "image": image
    });
    var response = await http.post(HttpConstants.UPLOAD_PRODUCT_BANNER_IMAGE,data: formData);
    return ImageBean.fromJson(response.data);
  }

你可能感兴趣的:(Flutter)