简体   繁体   中英

uploading image using file_picker flutter to a nodejs server

I have an api which gives the following data as response:

{
    "status": 200,
    "msg": "Data Found",
    "data": {
        "id": 104,
        "firstName": "aaa",
        "lastName": "aaa",
        "surname": "aaa",
        "email": "email@email.care",
        "phone": "090909090",
        "age": "23",
        "gender": "M",
        "height": "163",
        "bloodGroup": null,
        "weight": "72",
        "status": null,
        "fileId": 228,
        "password": "pass",
        "file": {
            "id": 228,
            "filename": "images.jpg",
            "path": "user/images1613558976577.jpg",
            "alt": "shafa care"
        }
    },
    "success": true,
    "token": "some token",
    "userAccess": "some data"
}

The "file" parameter in the response is used to hold the image that the user uploads. For my update method, the user needs to pass their token as header for the update api. For updating the file parameter i have tried many different ways just to update the user image. The below code is using multipart form data to update the existing file image.

Future<AuthModel> updateImage(File imageFile, AuthModel authModel) async{
      final String _accessToken = '${authModel.token}';
  final String url =
      '${GlobalConfiguration().getString('api_base_url')}auth/user/update';

  var stream = new http.ByteStream(imageFile.openRead());
  var length = await imageFile.length();
  var uri = Uri.parse(url);
  var request = new http.MultipartRequest("POST", uri);
  request.headers['Authorization'] = _accessToken;
  // request.headers['Content-Type'] = 'multipart/form-data';
  var multipartFile = new http.MultipartFile('file', stream, length, filename: basename(imageFile.path));
  request.files.add(multipartFile);
  var response = await request.send();
  print("updating: " + response.statusCode.toString());
  response.stream.transform(utf8.decoder).listen((event) {
    currentUser = authModelFromJson(event);
    print("updating img: " + event);
  });
  return currentUser;
}

The above function does not update my file parameter even when the data is found. I just get the same old response. filepicker is also sending the correct image path that the user chooses from the gallery. I have also tried using http.client.post method using a token as the header and 'file' parameter as the body but then data is not found as the api only accepts form-data when an image is being uploaded.

It works in postman using form-data post method. 邮差

I am new to flutter and still learning. I have been stuck here for days without any solution. How can i update the file parameter from my flutter application? Any help is appreciated.

This is sample code. I hope this may help you !

 static Future<bool> uploadFileAsFormData(
      String url, File file) async {
    try {
      var uri = Uri.parse(_buildUrl(url));
      var request = http.MultipartRequest('POST', uri);
      request.files.add(await http.MultipartFile.fromPath('file', file.path));

      var res = await request.send();
      if (res.statusCode == 200) {
        return true;
      } else {
   
        return false;
      }
    } catch (err) {

      return false;
    }
  }

You can use this Dio to upload the image as shown by the following code :

Dio dio = Dio();

var formData = FormData();
for (var file in filePath) {
  formData.files.addAll([MapEntry("files", await MultipartFile.fromFile(file)),]);
  print(formData.length);
}

var response = await dio.post(url
    data: formData,
    options: Options(headers: {
      'Authorization': _accessToken
    }));

if(response.statusCode == 200){
print(response.data.toString();
}

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