Couldn't upload image to server in Flutter Web - file-upload

I've created a flutter application for android and web. In Flutter web, I tried to upload image to server just like it works with firebase. But it is not working somehow. I've seen some solutions for this task. But I wonder, what is actually wrong with my code.
final url = Uri.parse('$apiHeader/poststore');
String token = await getUserToken();
Map<String, String> headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var request = http.MultipartRequest("POST", url);
request.headers.addAll(headers);
request.fields['category_id'] = model.categoryId;
request.fields['title'] = model.title;
//I want to know about this section of the code, how can i make it work
if (kIsWeb) {
final fileBytes =
await model.image.readAsBytes(); // convert into bytes
var multipartFile = http.MultipartFile.fromBytes(
'fileName[]', fileBytes); // add bytes to multipart
request.files.add(multipartFile);
} else {
var multipartFile = await http.MultipartFile.fromPath(
'fileName[]', model.image.path);
request.files.add(multipartFile);
}
var response = await request.send();

Related

Getting error while framing request URL using appscript

I am trying to frame request for API using appscript.
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe"
let body = {
'"url"':'"https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg"'
};
const headers = {
'method' : 'POST',
'Host':'imagealttextcreation.cognitiveservices.azure.com',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key':'###',
'payload': body
};
var response = UrlFetchApp.fetch(url_string,headers)
Logger.log(response)
I am getting invalid request error. But the same thing is working when i try manually(attached image for same).
Am I missing something while forming this request in the appscript?
When tried manually using the browser the functionality works. i want help in correcting the request using appscript.
From the official document, in your script, how about the following modification?
Modified script:
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe";
let body = { url: "https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg" };
const options = {
headers: { "Ocp-Apim-Subscription-Key": "###" }, // Please set your value.
payload: JSON.stringify(body),
contentType: "application/json"
};
var response = UrlFetchApp.fetch(url_string, options);
Logger.log(response.getContentText())
Reference:
fetch(url, params)

call api on local server in flutter

this is my code to get data from api in flutter but I received statuscode: 400!!!
please help.
void getProductList(String action, List<Product> list) async {
if (list.length == 0) {
var url = "http://10.0.2.2:8000/api/product";
final http.Response response= await http.get(url);
print(response.statusCode);
if (response.statusCode == 200) {
List jsonResponse = convert.jsonDecode(response.body);
for (int i = 0; i < jsonResponse.length; i++) {
setState(() {
list.add(new Product(title: jsonResponse[i]['title'],
img_url: jsonResponse[i]['img_url'],
price: int.parse(jsonResponse[i]['price'])));
});
}
}
}
}
Update
try requesting another endpoint to see if the problem is in your local server, try this:
var url = "https://jsonplaceholder.typicode.com/todos/1";
final response= await http.get(url);
print(response.statusCode);
if it worked then the problem is server-side.
Old Answer
If it's giving you StatusCode 400 then it means that the server is working fine, so probably the problem is in the request itself, try adding headers to your request.
await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
);
if this was not the issue, can you please add the error message!

flutter send empty file to server

Hi i'm trying to upload a file to a server via a flutter app but the file is always empty.
it was working fine and after that it stopped working.
here is my code :
static uploadImageToServer(String image) async {
File imageFile = new File(image);
Map<String, String> headers = {
'Content-Type': 'multipart/form-data',
'Accept-Charset': 'UTF-8'
};
var stream = new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
print(imageFile.path);
var uri = Uri.parse("http://planning.test/test_image");
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('File', stream, length,
filename: "test_image_failure.jpg");
request.headers.addAll(headers);
request.fields['Destination'] = '/';
print("**********");
print(multipartFile.filename);
print(uri);
print(multipartFile.length);
print("**********");
request.files.add(multipartFile);
print(request.contentLength);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
and with dio package
_dioUpload(String imageFile)async {
var dio = Dio();
var formData = FormData();
formData.files.add(MapEntry(
"File",
await MultipartFile.fromFile(imageFile, filename: "xx.png"),
));
print(formData.files.first.value.length);
var response = await dio.post(
"http://planning.test/test_image",
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + "%");
}
},
);
print(response);
}
i don't understand what is happening everything look fine and the file exist.
thx
I'm using the retrofit for flutter and to send an empty file I got it as follows.
File.fromRawPath(Uint8List.fromList([0]))
Retrofit example
#PUT('profile')
#FormUrlEncoded()
Future<void> update(#Header("Authorization") String token,
#Field() String name, #Field() String surname, #Part() File avatar);
Example
await myapi.update("_token_","Sr", "Burton", File.fromRawPath(Uint8List.fromList([0])));

Find out Cookie in Flutter

I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}

How to reduce the api loading time flutter

I am using rest apis for displaying the data ,but for api loading it takes more time how can i reduce that time in flutter.
Future getData0() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
var receivedToken = "Bearer " + prefs.getString("BearerToken");
var receivedstoreid=prefs.getString("store_id");
http.Response res = await http.get(
"http://Domainname.com/api/rest/cart",
headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
},
);
Map mapRes = jsonDecode(res.body);
print('Response from server: $mapRes');
get_cart_item = GetCart.fromJson(mapRes);
print(get_cart_item.toJson());
I am calling the get and post apis like this way.