I tried check file for exists but on all case flutter can't found file from directory.
Code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocDir = await path_provider.getApplicationDocumentsDirectory();
var path1 = '/assets/images/text.txt';
var path2 = 'assets/images/text.txt';
var path3 = '${appDocDir.path}/assets/images/banner.png';
if (await File(path3).exists()) {
print("File exists");
} else {
print("File don't exists");
}
}
File pubspec.yaml:
flutter:
assets:
- assets/images/
- assets/icons/
Where I have error on my code?
Assets directory should be in project root path.
assets
lib
build
etc.
You should to write file names too:
text.txt, banner.png
flutter:
assets:
- assets/images/text.txt
- assets/images/banner.png
-
path3:
var path3 = '${appDocDir.path}/assets/images/banner.png';
You don't need to use path_provider to get image form assets dir.
Related
I'm the junior flutter developer, and I would like to seek your support.
Currently, I would need to update data in a local JSON file in Flutter as below.
{"title":"ករណី ពិនិត្យផ្ទៃពោះ",
"lists":[
{
"id":"127",
"faci_code":"20018",
"y_txt":"2022",
"m_txt":"1",
"ind_id":"1",
"qty":"100",
"rec_by":"od123456",
"rec_date":"2022-06-27 13:50:31",
"lock_txt":"0",
"sec_id":"1",
"ind_num":"1",
"ind_eng":"# of ANC 1",
"ind_kh":"ចំនួនស្រ្ដីបានពិនិត្យផ្ទៃពោះលើកទី១ទាំងអស់",
"HFAC_NAME":"Boeng Pram",
"HFAC_NAMEKh":"បឺងប្រាំ",
"OD_CODE":"201",
"OD_NAME":"Thma Koul",
"OD_NAME_KH":"ថ្មគោល",
"PRO_CODE":"2",
"PROVINCE":"Battambang",
"PROVINCE_KH":"បាត់ដំបង"
}]}
I have searched and tried multiple solutions, but I couldn't resolve this issue yet.
I hope someone can provide a solution in advance.
Regard, thanks.
You can't right files in project folders.
Try local storage.
I used path_provider package in this example for get application directory path to write json file on local storage.
1. Create data class
Note. this data class should match your stored json structure
class DataClass {
String name;
int age;
DataClass(this.name, this.age);
factory DataClass.fromJson(Map<String, dynamic> json) {
return DataClass(json['name'], json['age']);
}
Map<String, dynamic> toJson() {
return {
'name': name,
'age': age,
};
}
}
2.create and update json file
DataClass? updateJson;
void createJson() async {
String data = await rootBundle.loadString('assets/data.json');
Directory appDocDir = await getApplicationDocumentsDirectory();
File jsonFile = File("${appDocDir.path}/data.json");
jsonFile.writeAsStringSync(data);
updateJson = DataClass.fromJson(jsonDecode(data));
setState(() {});
}
void updateJsonFile() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
File jsonFile = File("${appDocDir.path}/data.json");
//update
final jsonAsString = jsonFile.readAsStringSync();
updateJson = DataClass.fromJson(jsonDecode(jsonAsString));
updateJson?.name = "updated name";
updateJson?.age = _counter;
jsonFile.writeAsStringSync(jsonEncode(updateJson?.toJson()));
setState(() {});
}
Here is the backend code for the download endpoint:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream);
for (Long id : ids) {
// Get the "generated" file using the id
zipOut.putNextEntry(new ZipEntry(generated.getName() + ".doc"));
InputStream inputStream = new ByteArrayInputStream(generated.getFile().getBytes(1, (int)generated.getFile().length()));
IOUtils.copy(inputStream, zipOut);
zipOut.closeEntry();
}
zipOut.close();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=File.zip");
byte[] zipBytes = byteArrayOutputStream.toByteArray();
OutputStream outputStream = response.getOutputStream();
outputStream.write(zipBytes);
outputStream.close();
response.flushBuffer();
And for the frontend, I am using axios and file-saver
import { saveAs } from "file-saver";
request.then((response: any) => {
const blob = new Blob([response.data], { type: "application/zip" });
saveAs(blob, "Report.zip");
});
I can download the zip file, but when I tried to open, I got the follwing error:
"An attempt was made to move the file pointer before the beginning of the file"
NOTE: There is no error on the backend. The zip file is downloaded successfully. But upon opening the zip file, the error pops up.
Please, try to rewrite it like that:
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=File.zip");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (Long id : ids) {
// Get the "generated" file using the id
zipOut.putNextEntry(new ZipEntry(generated.getName() + ".doc"));
InputStream inputStream = new ByteArrayInputStream(generated.getFile().getBytes(1, (int)generated.getFile().length()));
IOUtils.copy(inputStream, zipOut);
zipOut.closeEntry();
}
zipOut.close();
response.flushBuffer();
I have subfolders for each of my commands and I'm wondering how I would check the name of the command's folder without having to add code into the command file itself. I've tried folders.filter(folder => folder.includes(command) and I'm hoping there's a similar way that could help me.
const folders = fs.readdirSync(`./categories`);
for (const folder of folders) {
const files = fs.readdirSync(`./categories/${folder}`);
for (const file of files) {
const command = require(`./categories/${folder}/${file}`);
client.commands.set(command.name, command);
};
};
client.on("message", async message => {
if (command.args && !args.length) {
const commandArgs = new Discord.MessageEmbed()
.setAuthor(command.category) // HERE - how would i check what subfolder the given command is in?
.setTitle(command.name)
.setDescription(command.description);
}
//code...
});
You can simply add a property when retrieving it:
const command = require(`./categories/${folder}/${file}`);
command.folder = folder;
client.commands.set(command.name, command);
Now you can use it when referencing the object:
const commandArgs = new Discord.MessageEmbed()
.setTitle("From folder: " + command.folder);
i'm trying to download file using node.js and this is my code:
var file_url = req.body.filename;
var DOWNLOAD_DIR = './downloads/';
var options = {
host: url.parse(file_url).host,
port: 80,
path: url.parse(file_url).pathname
};
var file_name = url.parse(file_url).pathname.split('/').pop();
var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
http.get(options, function (resp) {
resp.on('data', function (data) {
file.write(data);
}).on('end', function () {
file.end();
console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
delet(file_url);
});
});
here i'm giving DOWNLOAD_DIR manually so it is downloading to that
directory as it is localhost not a problem, but when i'm uploading this
code into server then the file should be downloaded to that particular
user's machine, so how to give path dynamically to DOWNLOAD_DIR variable
if the Downloads folder is in home directory (and you want to download in Downloads folder), then you can use
var path = require('path');
var file_url = req.body.filename;
var DOWNLOAD_DIR = path.join(process.env.HOME || process.env.USERPROFILE, 'downloads/');
var file_name = url.parse(file_url).pathname.split('/').pop();
var file_path = path.join(DOWNLOAD_DIR,file_name);
var file = fs.createWriteStream(file_path);
PS: While dealing with paths and files, always use path module of nodejs to generate path.
I'm currently storing images within the webapp folder of my Lift project, which I know will cause problems in future.
val path = "src/main/webapp/files/"
And the code I'm using to save it:
case Full(file) =>
val holder = new File(path, "test.txt")
val output = new FileOutputStream(holder)
try {
output.write(file)
} finally {
output.close()
}
}
What I'm trying to do is save the to the server root in an easily manageable folder called files, so SERVER_ROOT/files outside of the project folder.
Firstly how would I access the path to the root of the server so I can save them there?
Secondly how would I serve these files from my app, so I can display them on a page?
Thanks in advance, any help much appreciated :)
You have to store file to exact place on filesystem according to absolute path. I have written this code and it works, so maybe it helps you:
def storeFile (file : FileParamHolder): Box[File] =
{
getBaseApplicationPath match
{
case Full(appBasePath) =>
{
var uploadDir = new File(appBasePath + "RELATIVE PATH TO YOUR UPLOAD DIR")
val uploadingFile = new File(uploadDir, file.fileName)
println("upload file to: " + uploadingFile.getAbsolutePath)
var output = new FileOutputStream(uploadingFile)
try
{
output.write(file.file)
}
catch
{
case e => println(e)
}
finally
{
output.close
output = null
}
Full(uploadingFile)
}
case _ => Empty
}
}
and this is my getBaseApplicationPath function which finds out absolute path of local machine (server or your devel PC):
def getBaseApplicationPath: Box[String] =
{
LiftRules.context match
{
case context: HTTPServletContext =>
{
var baseApp: String = context.ctx.getRealPath("/")
if(!baseApp.endsWith(File.separator))
baseApp = baseApp + File.separator
Full(baseApp)
}
case _ => Empty
}
}