how to upload files (pdf, doc / image) from file_picker to api server on flutter.
I have a project with flutter wanting to upload files from the selected data. to select a file I use file_picker. the following code to select a file.
void _openFileExplorer() async {
setState(() => _loadingPath = true);
try {
_directoryPath = null;
_paths = (await FilePicker.platform.pickFiles(
type: _pickingType,
allowMultiple: _multiPick,
allowedExtensions: ['jpg', 'pdf', 'doc', 'docx', 'png'],
))
?.files;
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print(ex);
}
if (!mounted) return;
setState(() {
_loadingPath = false;
_fileName = _paths != null ? _paths.map((e) => e.name).toString() : '...';
});
}
then how to upload it?
I'm using this function to upload file to my server
static Future<bool> _upload(File file, int id) async { var headers = {'Authorization': 'Bearer TOKEN'}; // remove headers if not wanted var request = http.MultipartRequest( 'POST', Uri.parse(BaseUrl + ADD_IMAGE_TO_PRODUCTS)); // your server url request.fields.addAll({'id': '$id'}); // any other fields required by your server request.files.add(await http.MultipartFile.fromPath('image', '${file.path}')); // file you want to upload request.headers.addAll(headers); http.StreamedResponse response = await request.send(); if (response.statusCode == 200) { print(await response.stream.bytesToString()); return true; } else { print(response.reasonPhrase); return false; } } }
http
packageimport 'package:http/http.dart' as http;
MultipartRequest
using default
constructorvar request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
http.MultipartFile(
'picture',
File(filename).readAsBytes().asStream(),
File(filename).lengthSync(),
filename: filename.split("/").last
)
);
var res = await request.send();
MultipartFile.fromBytes()
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
http.MultipartFile.fromBytes(
'picture',
File(filename).readAsBytesSync(),
filename: filename.split("/").last
)
);
var res = await request.send();
MultipartFile.fromPath()
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
await http.MultipartFile.fromPath(
'picture',
filename
)
);
var res = await request.send();
var request = http.MultipartRequest('POST', Uri.parse(url));
request.fields['key'] = 'value';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.