如何从API颤振本地存储图像和.mp3文件?



我已经从GET请求显示图像和播放音频。现在我需要在本地存储图像和mp3音频文件。有没有办法做到这一点。我需要存储的图像和音频文件列表。谢谢你!这是我从API获得响应的方式。

"data": [
{
"id": 1052,
"title": "1",
"audio_file": "",
"desc": null,
"display_title": 1,
"audio_src": null,
"image_src": "https://topik.com/storage/uploads/topik/images/20220620092536.jpg"
},
{
"id": 1053,
"title": "2",
"audio_file": "",
"desc": null,
"display_title": 1,
"audio_src": null,
"image_src": "https://topik.com/storage/uploads/topik/images/20220620092545.jpg"
},
]

您可以使用path和path_provider来实现这一点。您共享的Api响应的示例代码:

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

您可以通过将getApplicationDocumentsDirectory更改为其他内容来更改文件写入的路径。对于可用的路径,请查看path_provider。

您可以使用示例代码下载响应中的所有文件:

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

如果我的回答有帮助,请把我的回答标记为正确。谢谢你。

将json对象转换为dart对象后

使用

Internet_file包

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');
},
);

现在使用PathProvider

Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
print("temp path : " + tempDir.toString());
await writeToFile(bytes, '${tempPath}/filename.png');
print("written");

最新更新