Leancloud Rest Api 传图片文档:戳这里~
Dio 使用文档:戳这里~
最近有一个小项目,有一个需求是将图片存到 LeanCloud 后端云。具体代码:
1. 上传图片:
postImage(File image)async {
try {
BaseOptions options = new BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000,
);
options.headers['X-LC-Id'] = 'Leancloud 应用 id';
options.headers['X-LC-Key'] = 'Leancloud 应用 key';
options.headers['Content-Type'] = 'image/jpg';
Dio dioImage = new Dio(options);
Response response = await dioImage.post('文档中给出的链接',
data: {'pic.jpg':image.readAsBytesSync()});
print(response);
} catch (e) {
print(e);
}
}
2. 获取图片:
前一步中上传成功之后,会返回下面这样的一个 json 数据,可以通过返回的 url 下载存放在 Leancloud 的图片。
{ "size":13,
"bucket":"1qdney6b",
"url":"http://ac-1qdney6b.qiniudn.com/3zLG4o0d27MsCQ0qHGRg4JUKbaXU2fiE35HdhC8j.txt",
"name":"hello.txt",
"createdAt":"2014-10-14T05:55:57.455Z",
"objectId":"543cbaede4b07db196f50f3c"
}
传上去之后,点击文件的 url,看到的是这样的一个json数据:
下载代码:
/* 需要的参数:图片的 url */
/* 返回值:Uint8List类型的List,因为要通过Image.memory() 显示图片,而Image.memory()需要的参数是List<Uint8List> */
/*Uint8List 包含在库 dart:typed_data 内*/
getImage(String url) async{
try {
BaseOptions options = new BaseOptions(
connectTimeout: 5000,
receiveTimeout: 3000,
);
options.headers['X-LC-Id'] = 'LeanCloud 应用 Id';
options.headers['X-LC-Key'] = 'LeanCloud 应用 key';
options.headers['Content-Type'] = 'image/jpg';
Dio dioImage = new Dio(options);
Response response;
response = await dioImage.get(url);
print(response.toString());
Map<String, dynamic> user = json.decode(response.toString());
print(user['pic.jpg']);
List<dynamic> res = user['pic.jpg'];
List<int> _res = res.cast<int>();
var l = Uint8List.fromList(_res);
return l;
} catch (e) {
print(e);
}
}
这样,完了之后,就可以通过 Image.memory()显示图片了。