Flutter: отправка многокомпонентного запроса на api сервера node.js - PullRequest
0 голосов
/ 22 октября 2018

У меня есть приложение Flutter, где пользователи заполняют форму и добавляют изображения (до 5).Я хочу отправить эти полные данные на мой сервер node.js через API.

Вот мой код флаттера:

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 я получаю имя и фамилию, и она сохраняется, однако я не получаю никаких изображений.

1 Ответ

0 голосов
/ 30 апреля 2019

Я использую .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!');
  }
...