Flutter:如何发送带有后期请求的文件图像

时间:2020-05-19 17:27:07

标签: flutter-dependencies

我尝试过这个鳕鱼,但没有帮助! 我尝试了Dio库也没有帮助! 请帮助!!!!!!!

Future<void> uploadImage(File userImage) async {

    try {
      if (userImage == null) {
        return;
      }

      var stream =
        new http.ByteStream(DelegatingStream.typed(userImage.openRead()));
    // get file length
    var length = await userImage.length(); //imageFile is your image file
    Map<String, String> headers = {
          HttpHeaders.acceptHeader: APIData.acceptHeader,
          HttpHeaders.contentTypeHeader: APIData.contentType,
          HttpHeaders.authorizationHeader: 'Bearer ' + userToken,
    }; // ignore this headers if there is no authentication

    // string to uri
    var uri = Uri.parse(APIData.domainApiLink + 'users/$userId/profile-image');

    // create multipart request
    var request = new http.MultipartRequest("POST", uri);

  // multipart that takes file
    var multipartFileSign = new http.MultipartFile('profile_pic', stream, length,
        filename: basename(userImage.path));

    // add file to multipart
    request.files.add(multipartFileSign);

    //add headers
    request.headers.addAll(headers);

    //adding params
    request.fields['loginId'] = '12';
    request.fields['firstName'] = 'abc';
   // request.fields['lastName'] = 'efg';

    // send
    var response = await request.send();

    print(response.statusCode);

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);

    });

    } catch (error) {
      throw error;
    }
  }

0 个答案:

没有答案