Flutter : get the original link of shorten url - flutter

I have to fetch some url link, but the link is shorten like "shorturl.at/cpqCE".
I want to get the original link url in flutter.
How can I do this?
in Phph I found this :
function expandShortUrl($url) {
$headers = get_headers($url, 1);
return $headers['Location'];
}
// will echo https://deluxeblogtips.com
echo expandShortUrl($url);

Thanks to #RandalSchwartz I solved it by using :
getUrl(url) async {
final client = HttpClient();
var uri = Uri.parse(url);
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
while (response.isRedirect) {
response.drain();
final location = response.headers.value(HttpHeaders.locationHeader);
if (location != null) {
uri = uri.resolve(location);
request = await client.getUrl(uri);
// Set the body or headers as desired.
if (location.toString().contains('https://www.xxxxx.com')) {
return location.toString();
}
request.followRedirects = false;
response = await request.close();
}
}
}

you can also do it by just sending a normal post request with the short link and you will then get the response which includes the original/full URL.
e.g
var uri = Uri.parse(shortUrl);
try {
var response = await http.post(
uri,
headers: {"Accept": 'application/json'},
);
// with below code you get the full path of a short url
String fullPath = response.headers.entries.firstWhere((element) => element.key == "location").value;
print(fullPath);
} catch (e) {
print(e);
}
hope this can help your problem.

Related

How to upload image to server in flutter

How does uploading image to server works in flutter! The ImagePicker return a path to directory,what url should be sent to server and what url should be used to show image on app if I want to upload a png format with autorization token in form-data with key profile_image and to show the similar Image.Below is one of the multiple I tried..
asyncFileUpload(File file) async {
var request = http.MultipartRequest(
"POST",
_getUri(
'/profilepicture',
));
var token = getHeaders();
request.headers["authorization"] = token as String;
;
var pic = await http.MultipartFile.fromPath("profile_image", file.path);
request.files.add(pic);
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
print(responseString);
}
What you are sending to the server is .png file and what is supposed to be shown to the user is the image in the server(url path) not the url path from phone. Therefore if the response returns that url all you need to do is get hold of it in the NetworkImage('url') or Image.network('url')
Note: It would be easy if you first show the picked image in your view then have a button that does the submit to the server. If successful replace the image picked url with the url from the server
asyncFileUpload(File file) async {
try {
var request = http.MultipartRequest(
'POST',Uri.parse('url'));
var token = getHeaders();
request.headers["authorization"] = token as String;
request.headers.addAll({
'Content-Type': 'application/json'
});
//request.fields.addAll({
// 'user_id': userId,
//});
request.files.add(await http.MultipartFile.fromPath('profile_image',file.path));
var response = await request.send();
var serverResponse = await http.Response.fromStream(response);
final responseData = json.decode(serverResponse.body);
if(response.statusCode == 200 || response.statusCode == 201){
return responseData;
}else{
return responseData;
}
} catch (e) {
print("Error occurred: $e");
return Future.error(e);
}
}

I'm using flutter to update user in Strapi. While running the following code, I am only able to change other fields details but not image. Thank you

I am trying to do so using Multipartfile class. My field name in the strapi is profile_image. Other details are updated, but neither image is uploaded in the media library, nor image is updated for this particular record.
try {
var url = "${kAPIURL}users/${bodyData["id"]}";
var imageBytes = await image!.readAsBytes();
int length = imageBytes.length;
http.ByteStream byteStream = http.ByteStream(image.openRead());
Stream<List<int>> stream = byteStream.cast();
var request = http.MultipartRequest('PUT', Uri.parse(url));
request.headers['Authorization'] = 'Bearer ${bodyData["jwt"]}';
request.fields['id'] = bodyData['id'];
request.fields['username'] = bodyData['username'];
request.fields['specific_type'] = bodyData['specific_type'];
request.fields['sex'] = bodyData['sex'];
request.fields['phone_number'] = bodyData['phone_number'];
request.fields['email'] = bodyData['email'];
var profileImage = http.MultipartFile(
'files.profile_image', stream, length,
filename: image.path.split('/').last.toString(),
contentType: MediaType('image', 'jpg'));
request.files.add(profileImage);
var response = await request.send();
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
if (response.statusCode == 200) {
Provider.of<MainScreenProvider>(context, listen: false).isDeleteCache =
true;
return response;
} else {
return response;
}
} on Exception {
throw Exception("Unable to update user details.");
}

http MultipartRequest file not receiving in server

I'm trying to upload image to my server but it's not receiving in my server when I upload file from app. But if I upload via postman it works but not from simulator
My Code
final request = http.MultipartRequest(
'POST', Uri.parse(''));
request.fields['title'] = title.text;
request.fields['sub_title'] = subTitle.text;
request.files
.add(await http.MultipartFile.fromPath('profile_photo', photo.path));
request.files
.add(await http.MultipartFile.fromPath('profile_video', video.path));
var response = await request.send();
var responseString = await response.stream.bytesToString();
print(responseString);
`
Output
{'title': 'zia', 'sub_title' : 'sultan', 'profile_photo' : {}, 'profile_video' : {}}
I too faced a similar issue and here is the solution to how I fixed it:
var fileExtension = AppUtils.getFileExtension(filePath);
if (fileExtension.isEmpty) {
AppUtils.showToast('File extension was not found');
return false;
}
final file = await http.MultipartFile.fromPath('vid', filePath,
contentType: MediaType('application', fileExtension));
request.files.add(file);
var res = await request.send();
if (res.statusCode == 200) {
final respString = await res.stream.bytesToString();
debugPrint('respString: $respString');
}
AppUtils:
class AppUtils {
static String getFileExtension(String filePath) {
try {
int index = filePath.lastIndexOf('.');
return filePath.substring(index + 1);
} catch (e) {
return '';
}
}
}

Invalid request payload input on flutter post request

I am trying to uploading multiple files from my flutter mobile app. Here is my screenshot of the postman. This works fine on postMan. But I am getting 400 errors on the flutter mobile app. I can't find out where is the problem?
Now here is the code of my flutter mobile app upload.
if(images.length>0){
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
String fileName = path.split('/').last;
var file = await MultipartFile.fromFile(path, filename:fileName);
multipart.add(file);
}
FormData imageFormData = FormData.fromMap(
{
"feedId": value.id,
"images": multipart,
"userInformationsId": value.userInformationId
});
print(multipart.length);
uploadFeedPicture(imageFormData);
}
Future<String> uploadFeedPicture(FormData _imageformData) async{
String at = await _apiProvider.getAccessToken();
Dio dio = new Dio();
// dio.options.headers['accept'] = 'application/json';
// dio.options.headers["content-Type"] = "multipart/form-data";
dio.options.headers["Authorization"] = "Bearer ${at}";
dio.options.baseUrl = getBaseUrl();
var _baseUrl = getBaseUrl();
await dio.post('/api/feed/upload', data: _imageformData, options: Options(
followRedirects: false,
validateStatus: (status) { return status < 500; }
), onSendProgress: (int sent, int total) {
print("$sent $total");
},).then((value) {
print(value.data);
print(value.headers);
}
).catchError((error) => print(error) );
}
And I am getting this response.
{statusCode: 400, error: Bad Request, message: Invalid request payload input}
Please Help me out where is the problem? I try with change content-type but not working.
After trying so many different ways I found the solution. Here it is.
if(value.id != null){
String at = await _apiProvider.getAccessToken();
Map<String, String> headers = { "Authorization": "Bearer ${at}"};
var uri = Uri.parse('$baseUrl/api/feed/upload');
var request = http.MultipartRequest('POST', uri);
request.headers.addAll(headers);
if(images.length>0){
for (int i = 0; i < images.length; i++) {
var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
// String fileName = path.split('/').last;
var file = await MultipartFile.fromPath("images",path);
request.files.add(file);
}
request..fields['feedId'] = value.id;
request..fields['userInformationsId'] = value.userInformationId;
var response = await request.send();
if (response.statusCode == 200) {
Navigator.pop(context);
showSuccessToast("Posted succesfull");
counter.update(0);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
}else{
showErrorToast("Upload image failed");
}
}
}

How do I upload image in Flutter App to my server and decode the json response from the server?

I have an Endpoint on my server which accepts multipart/form-data and sends back json as a response.
I want to send an Image from my flutter App to my server and Decode the json received from the server.
You can use http.MultipartRequest for that
Example:-
static Future<UploadImageRes> uploadImage(int id, File imageFile) async {
if (imageFile != null) {
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);
var uri = Uri.parse(UrlConstants.ADD_RECIPE_PHOTO);
LogUtils.d("====uri : $uri");
LogUtils.d("====recipeId : $id");
var request = new http.MultipartRequest("POST", uri);
String fileName = imageFile.path.split("/").last;
var multipartFile = new http.MultipartFile('photo', stream, length,
filename: fileName, contentType: new MediaType('image', 'jpeg'));
request.headers.addAll({"Authorization": "Bearer $token"});
request.files.add(multipartFile);
request.fields["recipeId"] = "$id";
var response = await request.send();
var statusCode = response.statusCode;
LogUtils.d("====statusCode : $statusCode");
if (statusCode < 200 || statusCode >= 400) {
throw new ApiException("Uploading failed");
}
final respStr = await response.stream.bytesToString();
return Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr)));
} else {
throw new ApiException("Uploading failed");
}
}
In final respStr = await response.stream.bytesToString(); you will get your api response