Flutter http request upload mp3 file
2,959
Please use flutter_upload package for uploading file
Or use below code for uploading the file using multipart :
static Future<String> fileUploadMultipart(
{File file, OnUploadProgressCallback onUploadProgress}) async {
assert(file != null);
final url = '$baseUrl/api/file';
final httpClient = getHttpClient();
final request = await httpClient.postUrl(Uri.parse(url));
int byteCount = 0;
var multipart = await http.MultipartFile.fromPath(fileUtil.basename(file.path), file.path);
// final fileStreamFile = file.openRead();
// var multipart = MultipartFile("file", fileStreamFile, file.lengthSync(),
// filename: fileUtil.basename(file.path));
var requestMultipart = http.MultipartRequest("", Uri.parse("uri"));
requestMultipart.files.add(multipart);
var msStream = requestMultipart.finalize();
var totalByteLength = requestMultipart.contentLength;
request.contentLength = totalByteLength;
request.headers.set(
HttpHeaders.contentTypeHeader, requestMultipart.headers[HttpHeaders.contentTypeHeader]);
Stream<List<int>> streamUpload = msStream.transform(
new StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data);
byteCount += data.length;
if (onUploadProgress != null) {
onUploadProgress(byteCount, totalByteLength);
// CALL STATUS CALLBACK;
}
},
handleError: (error, stack, sink) {
throw error;
},
handleDone: (sink) {
sink.close();
// UPLOAD DONE;
},
),
);
await request.addStream(streamUpload);
final httpResponse = await request.close();
//
var statusCode = httpResponse.statusCode;
if (statusCode ~/ 100 != 2) {
throw Exception('Error uploading file, Status code: ${httpResponse.statusCode}');
} else {
return await readResponseAsString(httpResponse);
}
}
Author by
Yasser
Updated on December 17, 2022Comments
-
Yasser over 1 year
Im using this api to upload a mp3 file
using this method
Future<void> uploadRecord(String matchId, String filePath) async { Uri url = Uri.parse( Urls.baseurl + EndPoints.uploadRecordEndPoint + '${auth.token}'); final request = http.MultipartRequest('POST', url) ..fields['match_id'] = matchId ..files.add(http.MultipartFile.fromBytes( 'file', await File.fromUri(Uri(path: filePath)).readAsBytes(), contentType: MediaType('audio', 'mpeg'))); final response = await request.send(); final responseStr = await response.stream.bytesToString(); print(responseStr); }
but it doesn't work, it seems that no file uploading, am i missing something ? or is there any better solution ?
-
Richard Heap over 4 yearsThis won't fix your problem, but you should use the other named constructor of MultipartFile that takes a file rather than bytes. Save the step of reading the file.
-