Reputation: 2795
I am trying to upload image to a server.
I have tested the API using postman and it is working correctly.
I found following type of code in many sites but for some reason it is not working for me. I get 400 status code error.
Can anyone point out what I am doing wrong?
var url = serverUrl + "/users/profile/upload-pic";
String basicAuth = 'Bearer ' + auth.token;
var postUri = Uri.parse(url);
var request = new http.MultipartRequest("POST", postUri);
request.headers['authorization'] = basicAuth;
request.files.add(
new http.MultipartFile.fromBytes(
'file',
await file.readAsBytes(),
contentType: new MediaType('image', 'jpeg'),
),
);
final response = await request.send();
print('Response status: ${response.statusCode}');
Upvotes: 1
Views: 1429
Reputation: 398
Use Dio package and send data with FormData.
For example:
Future<dynamic> _uploadFile(rawFilePath) async {
final filebasename = p.basename(rawFilePath);
var response;
try {
FormData formData = new FormData.fromMap({
"image_id": 123456,
"imageFile": await MultipartFile.fromFile(rawFilePath, filename: filebasename),
});
var url = serverUrl + "/users/profile/upload-pic";
var dio = Dio();
response = await dio.post(url , data: formData );
print('Response status: ${response.statusCode}');
} catch (e) {
print("Error reason: $e");
}
return response;
}
Upvotes: 0
Reputation: 1960
Upload(File imageFile) async {
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
String basicAuth = 'Token ' + auth.token; // you have to use Token while parsing Bearer token
var uri = Uri.parse(serverUrl + "/users/profile/upload-pic");
uri.headers['authorization'] = basicAuth;
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Upvotes: 1