将图像上传到服务器(Flutter)

时间:2019-11-23 19:53:29

标签: flutter mobile

请帮助将图片作为formData发送到服务器。我尝试将dio包中的FormData用于http请求,但无法正确发送图像。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

sendImage(File image) async {
    String fileName = imageFile.path.split("/").last;
    Uri uri = Uri.parse('Insert your server url here');
    var request = new http.MultipartRequest("POST", uri);
    List<int> fileBytes = await File(imageFile.path).readAsBytes();
    var multipartFile = new http.MultipartFile.fromBytes(
      'image', // (You can use another key instead 'image')
      fileBytes,
      filename: fileName,
    );
    request.files.add(multipartFile);
    // If you use token in headers use Authorization header
    request.headers.addAll(
      {'Authorization': 'Bearer ' + 'Your token'},
    );
    //
    var response = await request.send();
  }