选取图片
void pickImage() async {final input = html.FileUploadInputElement();input.multiple = false;input.accept = 'image/*';html.document.body?.append(input);input.click();await input.onChange.first;final files = input.files;if (files?.first.name.isEmpty == true) {return;}final file = files!.first;if (!await beforeUpload(file)) {input.remove();return;}final reader = html.FileReader();reader.onLoadEnd.listen((e) {final result = reader.result as Uint8List;uploadImage(result, file);});reader.readAsArrayBuffer(file);}
校验图片合法性
Future<bool> beforeUpload(html.File file) async {final size = await file.size;bool isSize = size / 1024 / 1024 < 15;if (!isSize) {print("超过15M限制,不允许上传~");return false;}final suffix =file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();final isSuffixByJpgOrPng =(suffix == 'jpg' || suffix == 'jpeg' || suffix == 'png');final isJpgOrPng = file.type == 'image/jpg' ||file.type == 'image/jpeg' ||file.type == 'image/png';if (!isSuffixByJpgOrPng || !isJpgOrPng) {print("只能上传JPG、JPEG、PNG格式的图片~'");return false;}return true;}
使用http上传图片
void uploadImage(Uint8List data, html.File file) async {try {var request = http.MultipartRequest('POST', Uri.parse('https://cdn.server.com/api/upload'));request.files.add(http.MultipartFile.fromBytes('file', data,filename: file.name, contentType: MediaType.parse(file.type)));final response = await request.send();if (response.statusCode == 200) {final jsonStr = await response.stream.bytesToString();final jsonData = jsonDecode(jsonStr);}} catch (e) {print("upload error -> $e");}}