简体   繁体   中英

How to upload image to server with Flutter

I am trying to upload image to a server.

I have tested the API using postman and it is working correctly.

I found following type of code in many sites but for some reason it is not working for me. I get 400 status code error.

Can anyone point out what I am doing wrong?

  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}');
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);
      });
    }

Use Dio package and send data with FormData.

For example:

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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM