一. 二進(jìn)制流圖像的顯示
前端圖像的展示,我們最常用的是給定一個圖像地址庇绽,然后它就會自己加載并顯示锡搜,如這樣的代碼:
<img src='圖像地址'/>
這基本是一種數(shù)據(jù)的Get請求,對于像Post之類的請求方式瞧掺,上述方式就不好用了耕餐,這個時候可以列用數(shù)據(jù)流或二進(jìn)制方式處理,在Flutter可以像下面文章處理:
但是此文的方法已經(jīng)過期了肠缔,我調(diào)整了一下(里面有額外獲取Headers的代碼夏跷,可去掉)
///
/// 獲取圖片
static Future getImage(String url) async {
Dio dio = Dio();
// 注意:這里使用bytes
dio.options.responseType = ResponseType.bytes;
// 如果headers有東西,則添加
Map<String, dynamic> headers = Map();
dio.options.headers = headers;
try {
Response response = await dio.post(url);
String codeId = '';
// 獲取response的headers信息明未,如果業(yè)務(wù)不需要可以去掉
final List<String> imageCode = response.headers["code-id"];
if (imageCode != null && imageCode.length > 0) {
codeId = imageCode[0];
}
final Uint8List bytes = consolidateHttpClientResponseBytes(response.data);
print("獲取圖像成功");
print(codeId);
return ImageCodeModel(codeId, bytes);
} catch (e) {
print("網(wǎng)絡(luò)錯誤:" + e.toString());
return await null;
}
}
static consolidateHttpClientResponseBytes(data) {
// response.contentLength is not trustworthy when GZIP is involved
// or other cases where an intermediate transformer has been applied
// to the stream.
final List<List<int>> chunks = <List<int>>[];
int contentLength = 0;
chunks.add(data);
contentLength += data.length;
final Uint8List bytes = Uint8List(contentLength);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
return bytes;
}
二. 圖像的上傳
對于圖像的上傳槽华,網(wǎng)上一些文章是這樣寫的:
void upload(String url, File file) {
print(file.path);
Dio dio = Dio();
dio.post(url, data: FormData.from({'file': file}))
...
這種方式其實對于新版的Flutter和Dio也已經(jīng)不適用了,而是應(yīng)如下方式調(diào)用:
static const TIME_OUT = 60000;
static const CONTENT_TYPE_JSON = "application/json";
static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
///
///上傳文件
static Future uploadFile(String url, File file) async {
String path = file.path;
var fileData = await MultipartFile.fromFile(
path
);
FormData formData = FormData.fromMap({
"file": fileData,
});
Options options = new Options(method: "POST");
///超時
options.receiveTimeout = TIME_OUT;
Map<String, String> headers = new HashMap();
headers[Config.tokenName] = SPService.getToken();
headers[HttpHeaders.contentTypeHeader] = CONTENT_TYPE_FORM;
headers[HttpHeaders.acceptHeader] = CONTENT_TYPE_JSON;
options.headers = headers;
return request(url, formData, options: options);
}