Skip to content

Instantly share code, notes, and snippets.

@sankarcheppali
Created January 25, 2020 11:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sankarcheppali/f5a75285c3e873a87a858b45f88accd0 to your computer and use it in GitHub Desktop.
Save sankarcheppali/f5a75285c3e873a87a858b45f88accd0 to your computer and use it in GitHub Desktop.
dart file upload
import 'package:path/path.dart';
import 'dart:io';
import 'dart:async';
import 'package:dio/dio.dart';
/**
* accepts three parameters, the endpoint, formdata (except fiels),files (key,File)
* returns Response from server
*/
Future<Response> sendForm(
String url, Map<String, dynamic> data, Map<String, File> files) async {
Map<String, MultipartFile> fileMap = {};
for (MapEntry fileEntry in files.entries) {
File file = fileEntry.value;
String fileName = basename(file.path);
fileMap[fileEntry.key] =
MultipartFile(file.openRead(), await file.length(), filename: fileName);
}
data.addAll(fileMap);
var formData = FormData.fromMap(data);
Dio dio = new Dio();
return await dio.post(url,
data: formData, options: Options(contentType: 'multipart/form-data'));
}
/**
* accepts two parameters,the endpoint and the file
* returns Response from server
*/
Future<Response> sendFile(String url, File file) async {
Dio dio = new Dio();
var len = await file.length();
var response = await dio.post(url,
data: file.openRead(),
options: Options(headers: {
Headers.contentLengthHeader: len,
} // set content-length
));
return response;
}
@feyroozecode
Copy link

How to send a data to the server without filename field in the formData

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment