[英]Flutter Upload image with MultipartRequest inside specific body
I need to upload a list of attachments inside an array with this structure:我需要在具有以下结构的数组中上传附件列表:
[
'description' => ['sometimes', 'string'],
'attachments' => ['sometimes', 'array'],
'attachments.*.file' => ['required', 'file'],
]
I'm using package http, and to upload files only allow me to put inside 'files', i'm using this code and it works to upload a file inside files, but I need that structure.我正在使用 package http,并且上传文件只允许我放入“文件”,我正在使用此代码,它可以在文件中上传文件,但我需要这种结构。
if (json != null) {
request.fields.addAll(json);
}
for (var item in filesPath) {
request.files.add(await http.MultipartFile.fromPath(
'file',
item,
));
}
There is any way to achieve this with this plugin?有什么方法可以用这个插件实现这一点?
Please try this请试试这个
void uploadImage() async {
// Show loader
// open a byteStream
var stream = new
http.ByteStream(DelegatingStream.typed(file.openRead()));
// get file length
var length = await file.length();
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": token
}; // ignore this headers if there is no authentication
// string to uri
var uri = Uri.parse(Constants.BASE_URL);
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this
// to the API request
request.fields["orderId"] = orderID.toString();
// multipart that takes file.. here this "file" is a key of the
// API request
var multipartFile = new http.MultipartFile('file', stream,
length,
filename: basename(file.path));
//add headers
request.headers.addAll(headers);
// add file to multipart
request.files.add(multipartFile);
// send request to upload image
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
setState(() {
if (response.statusCode == 200) {
print('uploaded');
} else {
print('failed');
}
});
// Hide loader
});
}).catchError((e) {
print(e);
// Hide loader
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.