简体   繁体   English

使用 file_picker flutter 将图像上传到 nodejs 服务器

[英]uploading image using file_picker flutter to a nodejs server

I have an api which gives the following data as response:我有一个 api 提供以下数据作为响应:

{
    "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.响应中的“file”参数用于保存用户上传的图像。 For my update method, the user needs to pass their token as header for the update api.对于我的更新方法,用户需要将他们的令牌作为 header 传递给更新 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.上面的function即使找到数据也不更新我的文件参数。 I just get the same old response.我只是得到同样的旧回应。 filepicker is also sending the correct image path that the user chooses from the gallery. filepicker 还会发送用户从图库中选择的正确图像路径。 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.我也尝试使用 http.client.post 方法,使用令牌作为 header 和 'file' 参数作为正文,但随后找不到数据,因为 Z8A5DA52ED126447D359E70C05721A8.AAZ 仅接受上传的表格时接受图像

It works in postman using form-data post method.它使用表单数据发布方法在 postman 中工作。 邮差

I am new to flutter and still learning.我是 flutter 的新手,还在学习。 I have been stuck here for days without any solution.我被困在这里好几天没有任何解决办法。 How can i update the file parameter from my flutter application?如何从我的 flutter 应用程序更新文件参数? 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上传图像,如以下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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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