uploadImage method

Future<String> uploadImage(
  1. File file,
  2. {int maxWidth = 1200}
)

Upload a local file to Pik (https://2.pik.vn) server and return a url to the uploaded file.

file - File to be uploaded

maxWidth

  • Your image's width will be resized to this value (if needed)
  • It's because Pik server require your image width must less than or equal 1200 px

Implementation

Future<String> uploadImage(File file, {int maxWidth = 1200}) async {
  final ext = Utils.getFileExt(file.path);
  final imageData = Utils.resizeImageIfRequired(file, ext, maxWidth);
  final body = {'image': 'data:image/$ext;base64,${base64.encode(imageData)}'};
  final headers = {
    'Accept-Encoding': 'gzip, deflate',
    'x-requested-with': 'XMLHttpRequest',
    'user-agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
  };
  final options = Options(
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    headers: headers,
  );

  final response = await _dio.post('/', data: body, options: options);

  final Map<String, dynamic> json = _readResponseAsJson(response);
  final savedUrl = json['saved'];
  if (savedUrl == null || (savedUrl is bool && !savedUrl)) {
    throw Exception('Can\'t upload at the moment.');
  }
  return '$BASE_URL/$savedUrl';
}