I have displayed images and played audio from GET request. Now I need to store the images and .mp3 audio files locally. Is there any way to achieve this. I need to store List of images and audio files. Thank You. This is the way I get response from API.
"data": [
{
"id": 1052,
"title": "1",
"audio_file": "",
"image_file": "uploads/basicbooks/images/20220620092536.jpg",
"desc": null,
"display_title": 1,
"audio_src": null,
"image_src": "https://uklcubt.com/storage/uploads/basicbooks/images/20220620092536.jpg"
},
{
"id": 1053,
"title": "2",
"audio_file": "",
"image_file": "uploads/basicbooks/images/20220620092545.jpg",
"desc": null,
"display_title": 1,
"audio_src": null,
"image_src": "https://uklcubt.com/storage/uploads/basicbooks/images/20220620092545.jpg"
},
]
CodePudding user response:
You can use the path and path_provider to implement this. Sample code for the Api response you shared:
import 'dart:io';
import 'package:http/http.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
/// Returns the response from the api in a Map
Map getResponseMap(String apiUrl) {
var response = http.get(apiUrl);
Map responseMap = jsonDecode(response) as Map<String, dynamic>;
return responseMap;
}
/// Returns the list of files from the api response.
List<Map> getItemsListFromResponseMap(Map responseMap) {
var list = responseMap['data'];
return list.cast<Map>(); // cast the list to a list of Maps.
}
/// Returns the file name with extension.
String getFileNameFromUrl(String url) {
String fileName = url.split('/').toList().last;
return fileName;
}
Future<void> downloadAudioFromAPIResponse(Map singleResponseItem) async {
String audioUrl = singleResponseItem['audio_src'];
await saveNetworkFileToLocalDirectory(audioUrl); // Your file will be saved to the specified directoty in the [saveNetworkFileToLocalDirectory] function below.
}
Future<void> downloadImageFromAPIResponse(Map singleResponseItem) async {
String imgUrl = singleResponseItem['image_src'];
await saveNetworkFileToLocalDirectory(imgUrl); // Your file will be saved to the specified directoty in the [saveNetworkFileToLocalDirectory] function below.
}
Future<void> saveNetworkFileToLocalDirectory(String fileSrcUrl) async {
var response = await http.get(fileSrcUrl);
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String filePath = join(documentDirectory.path, getFileNameFromUrl(fileSrcUrl));
File file = new File(filePath);
await file.writeAsBytes(response.bodyBytes);
// The file has been written at the filePath specified, in this case,
// The app's document directory.
}
You can change the path to which the file is written by changing the getApplicationDocumentsDirectory
to something else. For available paths, check out path_provider.
You can use the sample code to download all the files in your response as:
Map mainResponse = getResponseMap("YourApiRequestUrlHere");
// Get list of all item in the response by API.
List<Map> individualItems = getItemsListFromResponseMap(mainResponse);
// pre-evalute the count to improve performance by not having to call .length every time the loop finishes execution.
int count = individualItems.length;
for (int i = 0; i < count; i ) {
Map item = individualItems[i]; // get a single item.
if(item['audio_src'] != null && item['image_src'] != null) {
await downloadAudioFromAPIResponse(item);
await downloadImageFromAPIResponse(item);
} else if (item['audio_src'] != null) {
await downloadAudioFromAPIResponse(item);
} else if (item['image_src'] != null) {
await downloadImageFromAPIResponse(item);
} else {
continue;
}
}
If my answer was helpful, please mark my answer as Correct. Thank you.
CodePudding user response:
After converting json object to dart object
use
Internet_file package
Uint8List bytes = await InternetFile.get(
data.image_src,
headers: headers, /* in case you want to set auth otherwise remove it*/
process: (percentage) {
print('downloadPercentage: $percentage');
},
);
Now use PathProvider
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
print("temp path : " tempDir.toString());
await writeToFile(bytes, '${tempPath}/filename.png');
print("written");