Unable to upload documents in iOS platform using flutter - flutter

I am trying to upload a document to our server using Dio and file_picker flutter framework. This is working properly in the android platform, but it does not work in iOS platform. Below I have mentioned the code with the exception detail. Please guide me in fixing this issue.
Future<ProfileSuccess> postUserRegister(Map params, String subURL) async {
if (params['image'] != null && params['image'] != '') {
String fileImageName = params['image'];
fileImageName = fileImageName
.split('/')
.last;
params['image'] = UploadFileInfo(File(params['image']), fileImageName);
}
else {
params['image'] = '';
}
if (params['security_certificate'] != null &&
params['security_certificate'] != '') {
String fileSecrityName = params['security_certificate'];
fileSecrityName = fileSecrityName
.split('/')
.last;
params['security_certificate'] =
UploadFileInfo(File(params['security_certificate']), fileSecrityName);
}
else {
params['security_certificate'] = '';
}
if (params['upload_resume'] != null && params['upload_resume'] != '') {
String fileResumeName = params['upload_resume'];
fileResumeName = fileResumeName
.split('/')
.last;
params['upload_resume'] =
UploadFileInfo(File(params['upload_resume']), fileResumeName);
}
else {
params['upload_resume'] = '';
}
try {
FormData formData = FormData.from(params);
Response response = await _dio
.post(AppBaseURL.baseURL + 'user/$subURL',
data: formData /*json.encode(params)*/,
options:
new Options(contentType: ContentType.parse(
"application/x-www-form-urlencoded")));
if (response.statusCode == 200 || response.statusCode == 201) {
final Map parsed = response.data;
return ProfileSuccess.fromJson(parsed);
} else if (response.statusCode == 422) {
return ProfileSuccess.withError("The email has already been taken");
} else
return ProfileSuccess.withError('Authentication Error');
}
on DioError catch (exception) {
if (exception == null || exception.type == DioErrorType.DEFAULT) {
return ProfileSuccess.withError(exception.message);
}
else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
exception.type == DioErrorType.CONNECT_TIMEOUT) {
return ProfileSuccess.withError(
"Couldn't connect, please ensure you have a stable network.");
}
else if (exception.response.statusCode == 422) {
return ProfileSuccess.withError("The email has already been taken");
}
else {
return ProfileSuccess.withError("Something went wrong");
}
}}
FileSystemException: Cannot retrieve length of file' (OS Error: No such file or directory, errno = 2)

Related

The function call is not returning null but still giving "null" to be returned error

I'm migrating my old version flutter code to latest version with null safety feature.
In a function call I am getting the error "The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type". I have enclosed my code in try catch block and in catch block I added rethrow statement to prevent null exception.
This is my code.
Future<Map<String, dynamic>> fetchTimeline(http.Client client) async {
try {
print('INVOICE URL: ${globals.ursl.getURL(URLS.GETINVOICEURL)}');
Response response;
Dio dio = new Dio();
response = await dio.get(globals.ursl.getURL(URLS.GETINVOICEURL));
print('INVOICE GET RESPONSE: $response');
if (response.statusCode == 200) {
Map mapobject = (json.decode(response.toString()));
var succes = mapobject['success'];
if (succes == 1) {
if (mapobject['Invoice'][0]['address'] == null ||
mapobject['Invoice'][0]['address'] == '') {
address = '';
} else {
address = mapobject['Invoice'][0]['address'];
}
if (mapobject['Invoice'][0]['contact'] == null ||
mapobject['Invoice'][0]['contact'] == '')
phone = '';
else
phone = mapobject['Invoice'][0]['contact'];
if (mapobject['Invoice'][0]['restaurant_name'] == null ||
mapobject['Invoice'][0]['restaurant_name'] == '') {
name = ' ';
} else {
name = mapobject['Invoice'][0]['restaurant_name'];
}
logo = mapobject['Invoice'][0]['logo'];
globals.invoiceData = mapobject['Invoice'][0];
startTime();
return mapobject['Invoice'][0];
} else {
return {};
}
}
} catch (error) {
client.close();
print("CONNECTION CLOSED: $error");
rethrow;
}
}
I have added rethrow in catch block but still error is there.
Anyone there to help me out.
Thanks
It's a little hard to see with all the nested if statements, but you aren't returning a Map<String, dynamic> in every branch. This condition if (response.statusCode == 200) { ... } does not have a corresponding else branch, and so if the statusCode is some value other than 200 you are not returning anything (which means you are implicitly returning null in that case).

for-in using dart Exception: type '_InternalLinkedHashMap<String, dynamic>

i am not familiar using For-in using dart, i use similar code in ts or angular and it work as expected, but get lost when use flutter and need more guidance to use it.
Future<int> datetransaction(String mid) async {
var url = 'http://callsomehttp.com/$mid';
var res = await http.get(url);
if (res.statusCode == 200) {
var dtpoint = json.decode(res.body);
var availabledate = [];
for (var key in dtpoint) {
var dateEle = dtpoint[key]['Balance']['date'];
if (availabledate.indexOf(dateEle) == -1) {
availabledate.add(dateEle);
totalSpending(dateEle, mid);
}
}
print('available data $availabledate');
var spen = totalTransaction.reduce((a, b) => a + b);
return spen ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
Future totalSpending (String date, String ckey) async {
var total = 0 ;
final String url = 'http://otherurl.com/$date';
final res = await http.get(url);
if (res.statusCode == 200) {
var pdata = json.decode(res.body);
for (var key in pdata) {
var el = pdata[key]['Transaction']['customer_code'];
var ttl = int.parse(pdata[key]['Transaction']['total']);
if( el == ckey) {
totalTransaction.add(ttl);
total = ttl ;
}
}
return total ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
any guidance to give a light , or other way to get the result really appreciate, thank you

Getting Error 413 when attach image in the http request to node server in ionic 3

I am working on App where it needs to upload up to 4 images with the other data (images are optional). While uploading multiple images with other data with Ionic Native HTTP request to the node server (APIs are created in nodejs) I am getting below error.
error:{"statusCode":413,"error":"Request Entity Too Large","message":"Payload content lenght greater than maximum allowed: 1048576"}
I have searched for the issue but didn't get solutions except this, but don't know how to apply it in my ionic 3 app.
This is my code.
openGallery(){
if (
this.thumb1 != "" &&
this.thumb2 != "" &&
this.thumb3 != "" &&
this.thumb4 != ""
) {
this.presentToast("You can not upload more than 4 images.");
return;
}
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
encodingType: this.camera.EncodingType.JPEG,
quality: 10,
destinationType: this.camera.DestinationType.DATA_URL
// destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then(imageData => {
let base64File = "data:image/jpeg;base64," + imageData;
if (this.Image_0 === null) {
this.Image_0 = base64File;
} else if (this.Image_1 === null) {
this.Image_1 = base64File;
} else if (this.Image_2 === null) {
this.Image_2 = base64File;
} else if (this.Image_3 === null) {
this.Image_3 = base64File;
}
let base64Image = base64File;
if (this.thumb1 == "") {
this.thumb1 = base64Image;
this.thumb1 = this.sanitizer.bypassSecurityTrustResourceUrl(
this.thumb1
);
} else if (this.thumb2 == "") {
this.thumb2 = base64Image;
this.thumb2 = this.sanitizer.bypassSecurityTrustResourceUrl(
this.thumb2
);
} else if (this.thumb3 == "") {
this.thumb3 = base64Image;
this.thumb3 = this.sanitizer.bypassSecurityTrustResourceUrl(
this.thumb3
);
} else if (this.thumb4 == "") {
this.thumb4 = base64Image;
this.thumb4 = this.sanitizer.bypassSecurityTrustResourceUrl(
this.thumb4
);
}
}).catch(e => {
console.log("Error while picking from gallery", e);
});
}
postForm(){
let loading = this.loadingCtrl.create({
spinner: "bubbles"
});
loading.present();
let myData: any = {
Type: 1,
CustomerId: this.CustomerId,
Rating: Rating,
Review: this.review.value.comment
};
if (this.Image_0 != null) {
myData.Image_0 = this.Image_0;
}
if (this.Image_1 != null) {
myData.Image_1 = this.Image_1;
}
if (this.Image_2 != null) {
myData.Image_1 = this.Image_2;
}
if (this.Image_3 != null) {
myData.Image_3 = this.Image_3;
}
this.http
.post(
global.apiUrl + "restaurants/" + this._id + "/reviews",
myData,
headers
)
.then(data => {
})
.catch(error => {
loading.dismiss();
alert(JSON.stringify(error, Object.getOwnPropertyNames(error)));
});
}
I am trying to find the solution since last few days but couldn't find the solution so, therefore, posting here.
Update: We are using Hapi server.
I've managed to accomplish the image upload. The mistake is that I haven't specified the height and width of the image.
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
mediaType: this.camera.MediaType.PICTURE,
targetWidth: 250,
targetHeight: 200,
correctOrientation: true
};

Using Post Request return a multiple values in Unity

I am new to Unity i have created a Post Request from that i want to return the Authentication-Token Header and authorization header and some required json data here is my code
private IEnumerator BasketId()
{
string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
{
yield return request.SendWebRequest();
string token = request.GetResponseHeader("Authentication-token");
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
}
else
{
string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
Debug.Log(obj.Uri);
Debug.Log("Authentication-Token: " + token);
yield return obj.Title;
yield return token;
}
}
}
so i could i return the values. Please help me.
Because Coroutine is not immediate (blocking) so you won't be able to return the response directly. What you need to do is to have an event or callback that will be called when your request completed.
Here is how you can achieve it by passing the callback as argument:
private IEnumerator GetBasketId(System.Action<string, BasketId> callback)
{
string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
if (callback != null)
{
callback(null, null);
}
// callback?.Invoke(null, null); // for short
}
else
{
if (callback != null)
{
string token = request.GetResponseHeader("Authentication-token");
string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
if (callback != null)
{
callback(token, obj);
}
// callback?.Invoke(token, obj); // for short
}
}
}
}
so when you want to start the request simply call something like:
StartCoroutine(GetBasketId((token, basketId) =>
{
if (string.IsNullOrEmpty(token))
{
// Handle error
}
else
{
// Handle success
Debug.Log("Token: " + token);
Debug.Log(basketId.Title);
}
});

About mybatis3.3 databaseId,the code is useless

I study the mybatis3.3 sources code and now I have a question:in the XMLMapperBuilder.databaseIdMatchesCurrent()
private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
if (requiredDatabaseId != null) {
if (!requiredDatabaseId.equals(databaseId)) {
return false;
}
} else {
if (databaseId != null) {
return false;
}
// skip this fragment if there is a previous one with a not null databaseId
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
}
return true;
}
if the (requiredDatabaseId == null && databaseId != null) ,then the function will return false.
So the code
if (this.sqlFragments.containsKey(id)) {
XNode context = this.sqlFragments.get(id);
if (context.getStringAttribute("databaseId") != null) {
return false;
}
}
certainly no way to return false and this code is useless.
I just want to questioning: I understand this, right?