【问题标题】:Flutter: send multipart request to node.js server apiFlutter:向node.js服务器api发送多部分请求
【发布时间】:2019-03-26 05:24:49
【问题描述】:

我有一个 Flutter 应用程序,用户可以在其中填写表单并添加图像(最多 5 个)。我想通过 API 将这些完整的数据发送到我的 node.js 服务器。

这是我的颤振代码:

List<File> _imageFileList = new List<File>();
var postUri = Uri.parse('https://myapi.herokuapp.com/api/user/new');
    var request = new http.MultipartRequest("POST", postUri);

    request.headers['Authorization'] = 'Bearer ' + prefs.getString("TOKEN");

    request.fields['first_name'] = _firstName;
    request.fields['last_name'] = _lastName;

    // add file to multipart
    request.files.add(
      new http.MultipartFile(
          'upl',
          new http.ByteStream(DelegatingStream.typed(_imageFileList[0].openRead())),
          await _imageFileList[0].length()
      )
    );

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

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

在我的 Node.js 应用程序中,我执行以下操作:

var s3 = new aws.S3();

var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'mybucketname',
        acl: 'public-read',
        key: function (req, file, cb) {
            console.log(file);
            cb(null, file.originalname);
        }
    })
});

router.post('/new', upload.array('upl'), (req, res) => {
    var userObj = req.body;
    userObj.uuid = uuidv4();
    User.create(userObj).then(user => {
        console.log('----- added user: ' + JSON.stringify(user));
        res.status(200).json({
            message : 'user added'
        });
    });
});

问题出在我的 API 调用中,我确实得到了名字和姓氏,并且它被保存了,但是我没有收到任何图像。

【问题讨论】:

  • 为什么要在节点 api 中检查 req.file?您根据您的请求将这些保存为 request.files
  • 对不起,它来自旧代码。我在发布问题时忘记将其删除。

标签: node.js dart flutter multipart


【解决方案1】:

我正在使用.fromPath,这是上传多个文件的代码。确保在标头中设置 'Content-Encoding' 并在后端接受相同的内容

uploadDocuments(int refId,String token, List<File> fileList) async {
    String url = '$baseURL/api/referral/documents/upload';
    var uri = Uri.parse(url);
    var request = http.MultipartRequest("POST", uri);

    request.headers['x-access-token'] = token;
    request.headers['Content-Encoding'] = "application/gzip";
    request.fields["referralId"] = "$refId";

    for (var item in fileList) {
      await http.MultipartFile.fromPath('files', item.path,
              contentType: MediaType('application', 'x-tar'))
          .then((onValue) {
        print(onValue);
        request.files.add(onValue);
      });
    }

    var response = await request.send();
    print(response);
    if (response.statusCode == 200) print('Uploaded!');
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多