Image data is not accepted in my API trough params - image

Hello I've been trying to convert an Image to base64 and send it to a specified API but whenever I post an Image, it won't accept the data, but when the image is null the data gets in. These are the example of the API data that has an Image in it:
"PostedPicture": "Images/Posted/PostPhoto_659.jpg"
And this is me trying to post it (Camera function):
Future<void> _pickImageFromCamera() async {
final PickedFile pickedFile =
await picker.getImage(source: ImageSource.camera);
setState(() {
this.imageFile = File(pickedFile.path);
});
List<int> imageBytes = imageFile.readAsBytesSync();
print("Disini imageBytesnya: $imageBytes");
image = base64Encode(imageBytes);
}
Api post:
Future<HttpClientRequest> postNewsFeed() async {
print(
"Here is the post Type: $type, ID: $dataId, News: $news, SRCDOC: $sourceDocType, PRVCY: $privacyType, IMAGE: $image");
final client = HttpClient();
final request = await client.postUrl(Uri.parse(
"http://xxx.xx.xxx.xx:xxx/Services/SocMed/SocMedSvc.ashx?Type=$type&strEmpNo=$dataId&strNews=${news.text.toString()}&strGroupCode=['$dataGroupCode']&strSourceDocType=$sourceDocType&strPrivacyType=$privacyType&strCreatedBy=$dataId&strEncodedImage=$image"));
request.headers
.set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
return request;
}
So basically I send the "image" to Params because the API uses params.

Related

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

POST REQUEST _CastError (type '_File' is not a subtype of type 'String' in type cast)

I've been struggling for days trying to make this thing work.
This POST method is to upload an image which should be a "File" and a caption.
The API requires:
PAYLOAD:
- caption
- image
HEADER
- AUTHENTICATION
I'm new to flutter and I've followed a lot of tutorials but nothing seems to work.
here's my code:
static Future<void> addPost(
BuildContext context, String caption, File image) async {
debugPrint("$image");
String imageFile = image.path.split("/").last;
debugPrint("$imageFile");
Utils().showRegisterProgressDialog(context);
final userData = {
"caption": caption,
"image" : image
};
final response = await http.post(
APIServices.HTTP_DOMAIN + APIServices.POST_ADD_NEW,
body: userData,
headers: {"Authentication": "Bearer " + Constants.token});
debugPrint("STATUS: ${response.statusCode}");
if (response.statusCode == 200) {
Utils().hidePostingDialog(context);
Utils().postSuccessDialog(context);
} else {
Utils().hidePostingDialog(context);
Utils().postErrorDialog(context);
}
print(response.body);
return response;
}
I'd appreciate any help and suggestions.
EDIT
I've also tried using MultipartRequest but it returns a statuscode of 500
here's my code:
static Future<void> addPost(
BuildContext context, String caption, File image) async {
Map<String, String> headers = {
"Authentication": "Bearer ${Constants.token}"
};
debugPrint("TOKEN : $headers");
Utils().showPostingDialog(context);
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
var url =
Uri.parse("${APIServices.HTTP_DOMAIN}${APIServices.POST_ADD_NEW}");
debugPrint("TOKEN : $stream");
debugPrint("TOKEN : $length");
debugPrint("TOKEN : $url");
final request = http.MultipartRequest("POST", url);
debugPrint("TOKEN : $request");
debugPrint("TOKEN : $image");
debugPrint("TOKEN : ${image.path}");
var multipartFile =
new http.MultipartFile('file', stream, length, filename: image.path);
debugPrint("TOKEN : ${multipartFile.contentType}");
request.fields['caption'] = caption;
request.headers.addAll(headers);
request.files.add(multipartFile);
var response = await request.send();
debugPrint("TOKEN : ${response.request}");
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Http error 500 is generally seen during a bad request.
I would recommend you to try the exact same request using Postman and see what the result is, you can also try and print the response.message which sometimes can tell you what you did wrong while formatting the request.
Some more advice: try using the DIO package, it is much simpler to format request in it, you can set the header once, also errors are properly formatted, and a bunch of more advanced features are available which are quite helpful.

Azure OCR RecognizePrintedTextInStreamAsync Invalid Image

I'm trying to use the Azure OCR API in Xamarin Forms. Here is the important bits of code. I'm using the ComputerVisionClient .net client
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = false
});
Img = new Image
{
Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
}),
};
using (var photoStream = file.GetStream())
{
var text = await _client.RecognizePrintedTextInStreamAsync(true, photoStream);
}
The Img is bound to an image on the view and it shows up when I take a picture so there is definetly an image. However RecognizePrintedTextInStreamAsync returns back "System.IO.FileNotFoundException: 'Invalid Image'" and I'm not sure why. Any ideas?
Edit. Added _client code
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
Called from my constructor and set as a global var
_client = Authenticate(endpoint, subscriptionKey);
Thanks

Flutter image upload to SpringBoot server not working

I'm trying to upload an image from my Flutter application using the following code:
Future<String> saveImage(File image) async {
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
String token = "blah"; //token for authentication
var uri = Uri.parse(url); //I get the URL from some config
Map<String, String> headers = { "Authorization": "Bearer $token", "content-type": "multipart/form-data" };
var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
var multipartFile = new http.MultipartFile('file', stream, length);
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
But this request fails on my spring-boot server with the following error:
{"timestamp":1562637369179,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/api/v1/user/photo"}
This is what my Java controller method looks like:
#RequestMapping(value = "/photo", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadImage(#RequestPart(required = true) #RequestParam("file") MultipartFile image) throws IOException {
}
I would like to mention that the method works if I use postman to upload an image. There seems to be something wrong with my flutter code.
Thanks for any help.
Figured it out. Instead of using the new http.MultipartFile() constructor I used this static method:
request.files.add(await http.MultipartFile.fromPath('file', image.path,
contentType: new MediaType('image', imageType)));

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