Flutter camera image to api - ios

I am at the Point where i call the Flutter Camera package, take a photo and save it temporary in my app using pathProvider. Now i want so upload this image to an api using the Dio package. My pathprovider is able to give me a String with the Path to the image. With this path i am able to display the Image using the Image widget from Flutter. however i am not able to send it to an api.
processImage(file) async {
print(file);
// /var/mobile/Containers/Data/Application/7915E945-4582-4586-8062-F73537283283/Library/Caches/2019-07-22 13:35:36.243335.png
var newfile = File(file);
Dio dio = new Dio();
FormData formData =
new FormData.from({"size": "auto", "image_file": newfile});
try {
final response = await dio.post(
"YYYYYYYYYYYY",
data: formData,
options: Options(
headers: {'X-Api-Key': 'XXXXXXX'},
),
onSendProgress: (int sent, int total) {
print("send $sent / $total");
},
onReceiveProgress: (int sent, int total) {
print("receive $sent / $total");
},
);
} on DioError catch (e) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx and is also not 304.
print(e);
}
// print(response);
}

The Dio library that has a class called UploadFileInfo which you can use for your case:
FormData formData =
new FormData.from({
"size": "auto",
"image_file": UploadFileInfo(newfile, "file_name.txt")},
);

Related

Trying to upload media to the Meta Whatsapp API but running into errors

Context: I need to send media templates in which I need to send local files. Thus I need to upload the files to the WhatsApp API to get the Media Id, which I can then use to send the message templates.
The issue: I am running into errors while sending the post request to the server through DART. However the same call is working when sent through postman. I have tried sending the data both as a JSON and as form-data, but both are returning errors. I am attaching the code below, as well as the errors I am facing. Any help is really appreciated.
Getting the file path
upload() async{
if(await Permission.storage.isGranted){
FilePickerResult? choice = await FilePicker.platform.pickFiles(allowMultiple: false);
String? path = choice?.files.single.path;
if(path != null){
uploadJson(path);
// uploadFormData(path);
}
}else{
Permission.storage.request();
}
}
Uploading JSON
uploadJson(String path) async{
File imgfile = File(path);
Uint8List imgbytes = await imgfile.readAsBytes();
String bs4str = base64.encode(imgbytes);
print(bs4str);
var headers = {
'Authorization': variables.authorizationToken,
"Content-Type": 'application/json',
};
var body = jsonEncode({
'file': '$bs4str;type=image/jpeg',
'messaging_product':'whatsapp'
});
Response response = await post(Uri.parse('${variables.baseURL}${variables.phoneNumberId}/media'), headers: headers, body: body);
print(response.body);
}
Uploading as Form-data
uploadFormData(String path) async {
var headers = {
'Authorization': 'Bearer EAAGtvNhUHUIBANf5KvyxnZCUKcRn3jTJgPZBR2AbbVhZBZBO7GjoDCnS26FQT6Nr6qdRV993ZCJEbGwiqZCdQ7TZBJX8S6KXQdOTgmSf9ue7GCEN1IL3yqfAUEIN1bw0nyvptHeZBFCsdfwpxZAcS1ZCbCdmqArZC81orVbYRkzJy1h7ChOAygmrchfFtJAapykZAadruFqOWwcVvtudMezse94zENBNVZA0k7pAZD',
};
var request = MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/106822672107550/media'));
request.fields.addAll({
'messaging_product': 'whatsapp'
});
request.files.add(await MultipartFile.fromPath('file', path));
request.headers.addAll(headers);
Response response = await Response.fromStream(await request.send());
print(response.body);
}
Error for JSON:
flutter: {"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AE72st2KT8wJFQ_wYvrcJY6"}}
Error for Form-Data:
flutter: {"error":{"message":"(#100) Param file must be a file with one of the following types: audio\/aac, audio\/mp4, audio\/mpeg, audio\/amr, audio\/ogg, audio\/opus, application\/vnd.ms-powerpoint, application\/msword, application\/vnd.openxmlformats-officedocument.wordprocessingml.document, application\/vnd.openxmlformats-officedocument.presentationml.presentation, application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application\/pdf, text\/plain, application\/vnd.ms-excel, image\/jpeg, image\/png, image\/webp, video\/mp4, video\/3gpp. Received file of type 'application\/octet-stream'.","type":"OAuthException","code":100,"fbtrace_id":"AfsxKl38CW7hUF_ixMzNha9"}}
The problem was with the Mime-type of the file. The Multi-Part file class needed the mime-type of the file to be declared while uploading the file, or the file was automatically being uploaded as an octlet-stream. The code to the working request is posted below.
var request = http.MultipartRequest('POST', Uri.parse('https://graph.facebook.com/v14.0/${variables.phoneNumberId}/media'));
request.headers.addAll({
'Authorization': variables.authorizationToken,
'Content-Type': 'multipart/form-data'
});
request.fields.addAll({
'messaging_product': 'whatsapp',
'type': 'application/pdf'
});
// The MIME type of the image or file
const mimeType = 'application/pdf';
// Open the image file
var file = File(path);
// Create a MultipartFile from the File object
final multipartFile = await http.MultipartFile.fromPath(
'file',
file.path,
contentType: MediaType.parse(mimeType),
);
// Create a request body containing the multipart file
request.files.add(multipartFile);
// Send the request
final response = await request.send();
// Check the response status code
if (response.statusCode == 200) {
String body = await response.stream.bytesToString();
var json = jsonDecode(body);
print(json['id']);
} else {
print(response.reasonPhrase);
}

Send post request in aqueduct dart

I have created a post request in aqueduct dart and it takes json as body parameter, and I need to send that request body to thirdparty api , upon getting response from third party api I need to return that response to user. I have updated the code and printed the response header and it says http 400 (bad request)
here is the code :
#override
Controller get entryPoint {
String dataRecieved;
var completer = new Completer();
var contents = new StringBuffer();
final router = Router();
// Prefer to use `link` instead of `linkFunction`.
// See: https://aqueduct.io/docs/http/request_controller/
router.route("/uploadurl").linkFunction((request) async {
final req = await request.body.decode();
// print( await request.body.decode());
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
var auth = 'Bearer ' +
'eyJ...';
await client
.postUrl(Uri.parse(
'https://<removed>/api/datalake/v3/generateDownloadObjectUrls'))
.then((HttpClientRequest requestSend) {
requestSend.headers
.add("Content-Type", "application/json; charset=UTF-8");
requestSend.headers.add("Authorization", auth);
// requestSend.headers.contentLength = request.body.length;
print(req);
requestSend.write(req);
return requestSend.close();
}).then((HttpClientResponse response) async {
print(await response.contentLength);
var resStream = response.transform(Utf8Decoder());
await for (var data in resStream) {
print('Received data: $data');
}
print(await response.statusCode);
}).catchError((e) {
print("Request error: $e"); // The only case
});
print(contents);
return Response.ok({"key": dataRecieved});
});
return router;
}
when I make a request from the postman , I get
{
"key": null
}
I think I am not able to send the correct request to third party API , because when I tested third party API from the postman, it was sending correct response
My pubspec.yaml file is :
name: proxydl
description: An empty Aqueduct application.
version: 0.0.1
author: stable|kernel <jobs#stablekernel.com>
environment:
sdk: ">=2.0.0 <3.0.0"
dependencies:
aqueduct: ^3.0.0
http: ^0.12.0+2
dev_dependencies:
test: ^1.0.0
aqueduct_test: ^1.0.0
This is what I am sending from postman as post request:
{
"paths": [
{
"path": "/f1/f2.log"
}
]
}
This is my first POC with Dart on the server side.
Upon further investigation I found the answer:
final req = await request.body.decode();
var envalue = json.encode(req);
For now, this worked, but I feel there might be a better answer for this

Processing an Image in Dart

I am currently trying to process an image on the server that was uploaded by a user. My goal is to take this image that was uploaded, process it on the server and then upload it to rackspace cloud files. I have had no luck in finding a way. I am hoping that someone can lead me into the correct direction.
Heres what I have so far on the server side for processing
Future < Null > handleUploadRequest(final HttpRequest httpRequest) async {
print('handle upload -------------------------');
var data;
await httpRequest.fold(new BytesBuilder(), (b, d) => b..add(d)).then((builder) {
data = builder.takeBytes();
String encodedData = JSON.encode(data);
int dataLength = encodedData.length;
// Uploading image to rackspace cloud files
// Here we have to send a request with username & api key to get an auth token
http.post(tokens, headers : {'Content-Type':'application/json'}, body: JSON.encode({"auth": {"RAX-KSKEY:apiKeyCredentials":{"username":"XXXXXXXXXXXXXXX","apiKey":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}}})).then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
return response;
}).then((response){
authResponse = JSON.decode(response.body);
String token = authResponse['access']['token']['id'];
/////////// This is where we upload the image to Rackspace ///////
var request = new http.MultipartRequest("PUT", Uri.parse('https://storage101.iad3.clouddrive.com/v1/MossoCloudFS_XXXXXXX/TestContainer/testimage.jpg'));
request.headers['X-Auth-Token'] = token;
request.headers['Content-Type'] = 'image/jpeg';
var stream = new http.ByteStream.fromBytes(data);
request.files.add(new http.MultipartFile('file', stream, data.length, filename: 'testfile.jpg', contentType: 'image/jpeg');
print('requesT: ${request}');
request.send().then((response) {
print(response.statusCode);
print(response.headers);
print(response.stream);
if (response.statusCode == 200) print("Uploaded!");
});
//// End of Upload to Rackspace //////////
print('Upload Complete!');
httpRequest.response.write(data);
await httpRequest.response.close();
}
The only issue right now is that in https://pub.dartlang.org/packages/http, I need to call the type MediaType in the parameter content-type. I have no idea how to call this. It seems like it is a factory inside a class? If I do not call a content-type then it defaults to octet-stream which cannot be opened from the cdn storage container.
Reference to this way of uploading is from How can I upload a PDF using Dart's HttpClient?
Looks like an missing return before http.put(...) and httpRequest.response.close();
Either you use await before each async call (call to functions which return a Future) or return each such Future to the caller to preserve order of execution. Without any of these the async execution is scheduled for later execution and the next line of your code is executed instead before the async code you called even started.
Update pure async/await implementation
import 'package:http/http.dart' as http;
import 'dart:async' show Future, Stream;
import 'dart:io';
Future<Null> handleUploadRequest(final HttpRequest httpRequest) async {
print('handle upload -------------------------');
print('httpRequest: ${httpRequest.headers}');
var data;
var builder = await httpRequest.fold(new BytesBuilder(), (b, d) => b..add(d));
data = builder.takeBytes();
print('bytes builder: ${data}');
// Uploading image to rackspace cloud files
var url =
'https://storage101.dfw1.clouddrive.com/v1/{accountnumber}/{container}/';
var response = await http.put(url,
headers: {
'X-Auth-Token': '{XXXXXXXXXAPI_KEYXXXXXXXXXX}',
'Content-Type': 'image/jpeg',
'Content-Length': '${httpRequest.headers.contentLength}',
},
body: data);
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
print('closing connection with data complete');
httpRequest.response.write(data);
await httpRequest.response.close();
}

How can I upload a PDF using Dart's HttpClient?

I need to post a PDF file to a remote REST API, and I can't for the life of me figure it out. No matter what I do, the server responds that I have not yet associated an object with the file parameter. Let's say that I have a PDF called test.pdf. This is what I've been doing so far:
// Using an HttpClientRequest named req
req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
sb.write('file=$fileData');
req.write(sb.toString());
return req.close();
Thus far, I've tried virtually every combination and encoding of the data that I write() to the request, but to no avail. I've tried sending it as codeUnits, I've tried encoding it using a UTF8.encode, I've tried encoding it using a Latin1Codec, everything. I'm stumped.
Any help would be greatly appreciated.
You can use MultipartRequest from the http package :
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john#doe.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
Try using the multipart/form-data header rather than x-www-form-urlencoded. This should be used for binary data, also can you show your full req request?
void uploadFile(File file) async {
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
MultipartFile multipartFile = await http.MultipartFile.fromPath(
'idDocumentOne_1',
file.path
);
// add file to multipart
request.files.add(multipartFile);
// send request to upload file
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
I used file picker to pick file.
Here is the codes for pick file.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'],
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
here file_picker flutter library.

Downloading a file using Dart GDrive api with authorized GET request

I'm coding in Dart and need to download a file (i.e. an image file) from google GDrive using OAuth2.0. I am at the point in my code where I have the downloadURL after having used the Dart drive_v2_api_browser client library.
I tried directly passing this to the "src" attribute
_image = new ImageElement(src: file.downloadUrl, width: file.imageMediaMetadata.width, height: file.imageMediaMetadata.height);
_image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
but that yielded a 403 forbidden error. That's when I realized I need to make an "authorized GET request". So I tried following the example listed on the Dart Auth pub package https://pub.dartlang.org/packages/google_oauth2_client, but I don't understand what it asking for.
This is what I am trying:
var auth = new oauth.SimpleOAuth2(_picker.Token.data);
var request = new HttpRequest();
request.onLoad.listen(onData_Request, onError: onError_Request, onDone: onDone_Request, cancelOnError: true);
request.open("request", file.downloadUrl);
auth.authenticate(request).then((request) => request.send());
but it keeps giving me an error:
token.... Method request is not allowed by Access-Control-Allow-Methods.
Does anyone have a working example of downloading a file through the Dart GDrive api relative to OAuth2.0?
Update: After Günter Zöchbauer help I was able to continue and convert the blob as such:
Adding this line to the request object:
_downloadRequest.responseType = "blob";
Allowed me to use a file reader:
void onData_Request(Event e) {
Blob response = _downloadRequest.response;
final FileReader reader = new FileReader();
reader.onLoad.listen((e) {
_handleData(reader);
});
reader.readAsArrayBuffer(response);
}
void _handleData(FileReader reader) {
Uint8List uintlist = new Uint8List.fromList(reader.result);
String charcodes = new String.fromCharCodes(uintlist);
_loadImage(_image, charcodes, 225, 225);
}
void _loadImage(ImageElement imageE, String data, int iWidth, int iHeight) {
_imageAsbase64 = window.btoa(data);
_image = new ImageElement(src: "data:image/png;base64," + _imageAsbase64, width: iWidth, height: iHeight);
_image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
}
void onData(Event e) {
print("success: ");
_context.drawImage(_image, 0, 0);
}
As the error message says request is not a valid HTTP method.
You need something like GET, PUT, POST, DELETE, ...
see also http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Resources