How to upload image to server with Flutter - image

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

Related

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

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...
}

Send graphql to the Post body in Restsharp automation

throwing the below error when I pass GraphQL to the AddParameter#
{"errors":[{"message":"Expected \u0060{\u0060 or \u0060[\u0060 as first syntax token.","locations":[{"line":1,"column":1}],"extensions":{"code":"EXEC_SYNTAX_ERROR"}}]}
RestClient restClient = new RestClient("https://xxxxxx");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + AccessToken);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/graphql","{\"query\":\"{\\n agreements(where : submissionId:\\\"180823\\\") }" + ParameterType.RequestBody);
var resp = restClient.Execute(request);
I had similar issue when using HttpClient. Solved by UTF8 encode the query.
var gql = #"{""query"": ""{something { field1, field2 } }""}";
var message = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxx/graphql")
{
Headers =
{
{"Authorization", token}
},
Content = new ByteArrayContent(Encoding.UTF8.GetBytes(gql))
{
Headers =
{
{"Content-Type", "application/json"}
}
}
};

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

Bad request when trying to upload file in angular 2 using spring as backend

Hello i am trying to upload a file immediately when selected. i am getting a bad request 400.
Failed to load resource: the server responded with a status of 400 (Bad Request)
My codes are below.
<input type="file" (change)="fileChange($event)" placeholder="Upload file" >
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
alert(ConnectionHelper.SERVER_URL
+ConnectionHelper.MEDIACHANNEL+ConnectionHelper.UPLOADFILE)
this._http.post(ConnectionHelper.SERVER_URL
+ConnectionHelper.MEDIACHANNEL+ConnectionHelper.UPLOADFILE, formData,options)
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
Spring controller
#RequestMapping(value = "/api/mediaChannel/logoUpload", method = RequestMethod.POST)
#ResponseBody
public String logoUpload(#RequestParam("fileUpload") MultipartFile file,HttpServletResponse res, MultipartHttpServletRequest req) {
WebUtil wu = new WebUtil(res, req);
wu.allowCrossSiteMessages();
if (file.isEmpty()) {
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get("images\\" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "successfull";
}
Hi you cannot able upload file using http post,instead of you need use xhr request
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
return new Promise((resolve, reject) => {
let formData: any = new FormData();
let xhr = new XMLHttpRequest();
formData.append('uploadFile', file, file.name);
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', 'JWT ' + localStorage.getItem('id_token'));//If you need pass authentication token
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
resolve(JSON.parse(xhr.responseText));
}
}
});
}
}

Null response Xamarin android application using web api

Hi I am just learning Xamarin android development and I just want to CRUD operation but I am stuck that I am unable to get any response from webapi. I have tested my api using SOAPUI and response is ok from that.
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = #"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = #"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}
this is api code and below is my android application code but I am getting null response exception.
public async Task SaveTodoItemAsync(string EmpCode)
{
try
{
string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";
var uri = new Uri(string.Format(url));
var json = JsonConvert.SerializeObject(EmpCode);
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(url, content);
var responses = response;
}
catch (Exception ex)
{
var w = ex.ToString();
}
}
I think we have problem here. You are trying to create content from string not from Json.
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
try this:
var content = new StringContent(json, Encoding.UTF8, "application/json");
Edit:
I cannot see your default headers so if you don't have them - just add.
client.DefaultRequestHeaders.Add("Accept", "application/json");

Resources