![](/img/trans.png)
[英]Handshake Exception when trying to upload a file using MultipartRequest in flutter
[英]Flutter Upload image with MultipartRequest inside specific body
我需要在具有以下結構的數組中上傳附件列表:
[
'description' => ['sometimes', 'string'],
'attachments' => ['sometimes', 'array'],
'attachments.*.file' => ['required', 'file'],
]
我正在使用 package http,並且上傳文件只允許我放入“文件”,我正在使用此代碼,它可以在文件中上傳文件,但我需要這種結構。
if (json != null) {
request.fields.addAll(json);
}
for (var item in filesPath) {
request.files.add(await http.MultipartFile.fromPath(
'file',
item,
));
}
有什么方法可以用這個插件實現這一點?
請試試這個
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.