如何使用Flutter将图像上传到服务器

时间:2020-10-02 18:33:12

标签: image flutter http file-upload

我正在尝试将图像上传到服务器。

我已经使用邮递员测试了API,并且可以正常工作。

我在许多站点中发现了以下代码类型,但由于某种原因,它对我不起作用。 我收到400状态代码错误。

有人可以指出我在做什么错吗?

  var url = serverUrl + "/users/profile/upload-pic";

  String basicAuth = 'Bearer ' + auth.token;

  var postUri = Uri.parse(url);

  var request = new http.MultipartRequest("POST", postUri);
  request.headers['authorization'] = basicAuth;
  request.files.add(
    new http.MultipartFile.fromBytes(
      'file',
      await file.readAsBytes(),
      contentType: new MediaType('image', 'jpeg'),
    ),
  );
  final response = await request.send();

  print('Response status: ${response.statusCode}');

2 个答案:

答案 0 :(得分:1)

Upload(File imageFile) async {    
    var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
      var length = await imageFile.length();
        String basicAuth = 'Token ' + auth.token; // you have to use Token while parsing Bearer token
      var uri = Uri.parse(serverUrl + "/users/profile/upload-pic");
         uri.headers['authorization'] = basicAuth;
     var request = new http.MultipartRequest("POST", uri);
      var multipartFile = new http.MultipartFile('file', stream, length,
          filename: basename(imageFile.path));
          //contentType: new MediaType('image', 'png'));

      request.files.add(multipartFile);
      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }

答案 1 :(得分:0)

使用Dio package并使用FormData发送数据。

例如:

Future<dynamic> _uploadFile(rawFilePath) async {
      final filebasename = p.basename(rawFilePath);

      var response;

      try {
        FormData formData = new FormData.fromMap({
          "image_id": 123456,
          "imageFile": await MultipartFile.fromFile(rawFilePath, filename: filebasename),
        });

        var url = serverUrl + "/users/profile/upload-pic";

        var dio = Dio();
        response = await dio.post(url , data: formData );

        print('Response status: ${response.statusCode}');

      } catch (e) {
        print("Error reason: $e");
      }

    return response;
  }