我有一个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调用中,我确实获得了名字和姓氏并将其保存,但是我没有收到任何图像。
答案 0 :(得分:0)
我正在使用.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!');
}