how to upload files (pdf, doc / image) from file_picker to api server on flutter

Viewed 5001

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 ?

2 Answers

Import http package

import 'package:http/http.dart' as http;

Create MultipartRequest using default constructor

var 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();

Using 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();

Using MultipartFile.fromPath()

  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(
    await http.MultipartFile.fromPath(
      'picture',
      filename
    )
  );
  var res = await request.send();

Adding Regular Text Fields

var request = http.MultipartRequest('POST', Uri.parse(url));
request.fields['key'] = 'value';

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;
    }
  }
}

Related