post image to server using http post multipart/form-data request [flutter-web] - image

I am trying to upload the image to server using http package,
here is the screenshot from postman
so far I have been following this link https://rodolfohernan20.blogspot.com/2019/12/upload-files-to-server-with-flutter-web.html
and here is part of the code to send the image
var url = Uri.parse("http:xxxxxxx");
var request = new http.MultipartRequest("POST", url);
request.headers.addAll(headers);
request.fields['user_id'] = '1';
request.fields['_method'] = 'put';
request.files.add(await http.MultipartFile.fromBytes(
'file', _imageFile,
contentType: new MediaType('application', 'octet-stream'),
filename: "example"));
request.send().then((response) {
print(response.statusCode);
if (response.statusCode == 200) print("sent");
});
imageFile is List of int(List<int>) where imageFile=Base64Decoder().convert(result.toString().split(",").last);
the respond that I get is always respond status= 400, is there a way to solve this?

You can try this way:
//URL
String baseUrl = "https:xxxxx";
var request = http.MultipartRequest('POST', Uri.parse(baseUrl));
request.headers.addAll(headers);
request.files.add(
http.MultipartFile(
'file',
File(_imageFile.path).readAsBytes().asStream(),
File(_imageFile.path).lengthSync(),
filename: _imageFile.path.split("/").last,
),
);
// Other fields
request.fields['user_id'] = '1';
request.fields['_method'] = 'put';
var response = await request.send();
if (response.statusCode == 200) {
// do something...
} else {
// do something...
}

Related

FormData not being read by laravel on backend

This qn is related to vue and alravel, I try to make and api request on vue with const response = await http.put("api/v1/vehicles/" + vehicleId,formData);. I see the data going on payload, But when i DO dd($request->all()) It shows empty
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
const response = await http.put(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
When I hit url with const response = await http.put("api/v1/vehicles/" + vehicleId,data); It shows on $request->all(). I need to add formData to attach the fiels. Is it because put request doesnot read formData??
I saw a method spoofing and I did this
let vehicle_data = { _method: "PUT", form: formData };
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
vehicle_data
);
BUt it gives null on form?
PUT and PATCH request types require adding a _method property in payload and using .post instead .put
Said that, you should do this:
async update(vehicleId, data) {
try {
let formData = new FormData();
(data.files ?? []).forEach((file, key) => {
formData.append("files[]", file);
});
Object.entries(data).forEach(([key, value]) => {
if (key !== "files" && value !== null) formData.append(key, value);
});
formData.append("_method", "PUT")
const response = await http.post(
"api/v1/vehicles/" + vehicleId,
formData
);
return Promise.resolve(response.formData);
} catch (err) {
return Promise.reject(err);
}
},
Please note that I've changed request to http.post() and added formData.append("_method", "PUT")
Your API will recognize it as a PUT request and also grab payload correctly.
The same should be done for PATCH requests.

How to upload image to server with Flutter

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}');
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);
});
}
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;
}

How to do multiple call using nexmo in-app voice?

Hello i try to create in app voice following this tutorial https://developer.nexmo.com/client-sdk/tutorials/app-to-phone/client-sdk/app-to-phone/js-code/javascript and combine it with laravel. Can it use to make multiple call like 3 users use it at the same times? it seems like when i try to use it for multiple call at the same times the connection use the same websocket.
This my javascript code:
// contact button on table 1
dataTableAdminLeader.on('click', '.call-button', function(){
$('#phone-call-modal').modal('show');
let id = $(this).data('id');
let master_number_id = $(this).data('master_numbers_id');
let target_number = $(this).data('number');
// input reset
document.querySelector('#target-phone').value = target_number;
document.querySelector('#master-number-id').value = master_number_id;
document.querySelector('#id-edit').value = id;
document.querySelector('#master-numbers-id-edit').value = master_number_id;
// ajax object
const xhr = new XMLHttpRequest();
// all constant needed for call
const USER_JWT = "{{ $jwt_token }}";
const phoneNumberInput = document.querySelector("#cs-phone");
const statusElement = document.querySelector("#status-call");
// button object selector
const callButton = document.querySelector(".btn-call");
const hangupButton = document.querySelector(".btn-hangup");
const updateButton = document.querySelector(".btn-update");
const closeButton = document.querySelector('.btn-close');
const statusButton = document.querySelector('.btn-status');
// input object selector
let campaign_result = document.querySelector('#campaignresult');
let note_contacted = document.querySelector('#note_contacted');
let note_container = document.querySelector('.note_container');
let campaignContainer = document.querySelector('.campaign-container');
// call status check
let callStatusCompleted = false;
let callStatusAnswered = false;
// reset property
campaign_result.value = "";
note_container.style = 'display: none';
// listening to event
campaign_result.addEventListener('change', function(){
if(campaign_result.value == 2){
note_container.style.removeProperty('display');
note_contacted.setAttribute('required', 'required');
}else{
note_container.style = 'display: none';
note_contacted.removeAttribute('required');
}
});
// nexmo status reset
statusElement.innerText = '';
// nexmo call button reset
callButton.style.display = "inline";
hangupButton.style.display = "none";
// timeouts set
setTimeout(() => {
callButton.removeAttribute('disabled');
}, 4000);
// nexmo object start
new NexmoClient({ debug: true }).login(USER_JWT).then(app => {
callButton.addEventListener("click", event => {
event.preventDefault();
let number = phoneNumberInput.value;
if (number !== ""){
app.callServer(number);
} else {
statusElement.innerText = 'Please enter your phone number.';
}
});
app.on("member:call", (member, call) => {
console.log('member:call:oke:',app);
// object selector reset
callButton.style.display = 'none';
closeButton.style.display = 'none';
hangupButton.style.removeProperty('display');
statusButton.style.removeProperty('display');
// event when hangup button clicked
hangupButton.addEventListener("click", () => {
call.hangUp();
});
});
app.on("call:status:changed",(call) => {
console.log('Periodik : ', call.status);
// animation call
let statusAnimation = `<p class="saving">Call status: ${call.status}<span>.</span><span>.</span><span>.</span></p>`;
// assign call animation to nexmo status display
statusElement.innerHTML = statusAnimation;
// filter nexmo status condition
switch(call.status) {
case call.CALL_STATUS.STARTED:
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.RINGING:
// ajax params
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.FAILED:
callStatusAnswered = false;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
closeButton.style.display = 'none';
statusButton.style.removeProperty('display');
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.CANCELLED:
callStatusAnswered = false;
callButton.style.removeProperty('display');
hangupButton.style.display = 'none';
closeButton.style.removeProperty('display');
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.BUSY:
callStatusAnswered = false;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
closeButton.style.removeProperty('display');
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.TIMEOUT:
callStatusAnswered = false;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
closeButton.style.removeProperty('display');
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.REJECTED:
callStatusAnswered = false;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
closeButton.style.removeProperty('display');
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.UNANSWERED:
callStatusAnswered = false;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
closeButton.style.removeProperty('display');
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.COMPLETED:
call.hangUp();
callStatusCompleted = true;
callButton.style.display = 'none';
hangupButton.style.display = 'none';
updateButton.style.removeProperty('display');
closeButton.style.display = 'none';
statusButton.style.display = 'none';
campaignContainer.style.removeProperty('display');
dataTableAdminLeader.ajax.reload();
console.log('Case call status: ', call.status);
break;
case call.CALL_STATUS.ANSWERED:
callStatusAnswered = true;
callButton.style.display = 'none';
hangupButton.style.removeProperty('display');
closeButton.style.display = 'none';
statusButton.style.display = 'none';
// ajax send
params = `id=${id}&master_number_id=${master_number_id}&status=${call.status}`;
xhr.open('POST', '{{ url('/call/update') }}', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
xhr.onload = function(){
let response = JSON.parse(this.responseText);
console.log('xhr: ',response);
}
console.log('Case call status: ', call.status);
break;
default:
console.log('Case call status: ', call.status);
}
});
}).catch(function(){
alert('Network Problem, refresh page and try again later. Please contact dev team if this problem not fix in few minutes.');
console.error;
$('#phone-call-modal').modal('hide');
});
});
You can make multiple outbound phone calls consecutively using the Vonage Voice API and the Client SDK. The function, callServer() takes a phone number you wish to call as the argument as documented in the Client SDK documentation.
The code you demonstrated above receives that phone number argument from the form input: const phoneNumberInput = document.querySelector("#cs-phone");. This is an input for one phone number. You would need to revise your form in your Laravel application to have multiple phone number inputs and loop through them in consecutive calls to callServer().
You can also read more about the Voice API and the various parameters and their data types on the API Reference Documentation.

Cypress - unable to store response.body data into a JSON file

I've created a POST XMLHttpRequest with FormData successfully. I now need to capture it's response body and get it stored in a JSON file.
Cypress.Commands.add(
"Post_Clients",
(imagePath, imageType, attr1, attr2, attr1Val, done) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const data = new FormData();
data.set(attr1, attr1Val);
data.set(attr2, blob);
xhr.open("POST", "https://api.teamapp.myhelpling.com/admin/clients");
xhr.responseType = "json"
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
done(xhr);
};
xhr.onerror = function() {
done(xhr);
};
xhr.send(data);
});
});
}
);
it.only("API POSTing TEST", () => {
cy.Post_Clients(
"/images/clients/Golden JPEG.jpeg",
"image/jpeg",
"client[name]",
"client[client_logo_attributes][content]",
"Test Attr 1 Value is Hi!!!",
resp => {
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",
resp.response
);
expect(response.status).to.eq(201);
}
);
});
Kindly note that expect(response.status).to.eq(201); assertion works well.
Following code logs the body properly in the console
cy.log("Response Body", resp.response);
console.log("Response Body", resp.response);
Response Body is: -
{"client":{"id":452,"name":"Test Attr 1 Value is Hi!!!","client_logo":{"id":543,"path":"https://api.teamapp.myhelpling.com/uploads/client_images/6279486665-1551780183.","thumb":"https://api.teamapp.myhelpling.com/uploads/client_images/thumb_6279486665-1551780183.","medium":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","large":"https://api.teamapp.myhelpling.com/uploads/client_images/medium_6279486665-1551780183.","filename":"blob","ratio":1.78}}}
but
cy.writeFile(
"cypress/fixtures/POST API OUTPUT DATA/Client.json",resp.response
);
doesn't save the response body in Client.JSON file.
cy.writeFile seems to not work in this code. I've verified this by
passing a JSON e.g. {"A":"B"} and that too didn't make it to the
JSON.
Thanks everyone for all you kind help. I've made it work by calling cy.writeFile inside onLoad event before triggering XHR request. Here's the code sample with some other updates that I've made for my other works: -
Cypress.Commands.add(
"Post_Bucket",
(imagePath, imageType, title, img, titleVal) => {
cy.fixture(imagePath, "binary").then(imageBin => {
Cypress.Blob.binaryStringToBlob(imageBin, imageType).then(blob => {
const xhr = new XMLHttpRequest();
const data = new FormData();
data.set(title, titleVal);
data.set(img, blob);
cy.readFile(Cypress.env("IDStore")).then(obj => {
xhr.open(
"POST",
Cypress.env("BucketPostURLPart1") +
obj.journeyID +
Cypress.env("BucketPostURLPart2"),
false
);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("access-token", accesstoken);
xhr.setRequestHeader("client", client);
xhr.setRequestHeader("expiry", expiry);
xhr.setRequestHeader("token-type", tokentype);
xhr.setRequestHeader("uid", uid);
xhr.onload = function() {
if (this.status === 201) {
cy.writeFile(
Cypress.env("BucketOutputFile"),
JSON.parse(this.responseText)
);
cy.readFile(Cypress.env("IDStore")).then(obj => {
obj.bucketID = JSON.parse(this.responseText).bucket.id;
cy.writeFile(Cypress.env("IDStore"), obj);
});
}
};
xhr.send(data);
});
});
});
}
);
This is the simple example try with this one.
cy.request('https://jsonplaceholder.cypress.io/users')
.then((response) => {
cy.writeFile('cypress/fixtures/users.json', response.body)
})

"405 (Method Not Allowed) and Response for preflight does not have HTTP ok status Error"

I'm building a simple web application and i'm making an XMLHttpRequest() POST request call to a URL that is hosted on Azure. I'm getting the following error:
"405 (Method Not Allowed)"
"Response for preflight does not have HTTP ok status Error"
I have also enabled my CORS extension on my browser. Below is my code:
var xhr = new XMLHttpRequest();
var url = "MyURL" // URL is Correct, I verified!
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log("Data is: " + json);
}
};
var obj = { SignId: getSignIdArr[temp] , BarCodeId: getBarCodeIdArr[temp],
BaseType: getBaseTypeArr[temp], Condition: getConditionArr[temp],
ConditionDate: getConditionDateArr[temp], Owner: getOwnerArr[temp],
Custodian: getCustodianArr[temp], FaceMaterial: getFaceMaterialArr[temp],
FacingDirection: getFacingDirectionArr[temp], Height: getHeightArr[temp],
Illuminated: getIlluminatedArr[temp], MountType: getMountTypeArr[temp],
Notes: getNotesArr[temp], Code: getCodeArr[temp],
Description: getDescriptionArr[temp], Dimensions: getDimensionsArr[temp],
Type: getTypeArr[temp], Status: getStatusArr[temp],
Support: getSupportArr[temp], RetroRefTextSymbol: getRetroRefTextSymbolArr[temp],
RetroRefBackground: getRetroRefBackgroundArr[temp],
RetroRefTestFailed: getRetroRefTestFailedArr[temp], MaterialCost: getMaterialCostArr[temp],
LabourCost: getLabourCostArr[temp], InstallationCost: getInstallationCostArr[temp],
ReflectiveCoating: getReflectiveCoatingArr[temp],
ReflectiveRating: getReflectiveRatingArr[temp],
OptimisticLockField: getOptimisticLockFieldArr[temp], GCRecord: getGCRecordArr[temp],
NewSupport: getNewSupportArr[temp], SignGroup: getSignGroupArr[temp],
RetroRefDate: getRetroRefDateArr[temp], EquipmentCost: getEquipmentCostArr[temp]
};
var data = JSON.stringify(obj);
xhr.send(data);
Any help will be greatly appreciated! Stuck in this for a while. Thanks all!

Resources