I am new to dart and am currently trying to create a file from a data String.
All looks good so far as the length is not 0. But when i open the file, it instantly closes again, no console output, no errors.
I'd appreciate any pointers in the right direction, if any information is missing, please point it out and i will provide if possible.
void createFile(data) async{
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = new File(tempPath+widget.tileText);
var sink = file.openWrite();
sink.write(data.codeUnits);
await sink.flush();
await sink.close();
print(await file.length());
OpenFile.open(file.path);
}
UPDATE: added flush() and await before close() - loading a little smoother now, but File still closes instantly
Update2: removed create() (was a misunderstanding on my part)
now getting console output when the File closes: D/EGL_emulation(23235): eglCreateContext: 0xef02d650: maj 2 min 0 rcv 2
Running i ton my phone gives no console log, instead a simple "Can't open File" from the viewing application,i doublechecked the Path, it looks ok and it exists
So i found 2 problems and solved it now:
The path was missing a "/"
I didn't format the data right, i had to decode it and use writeAsBytes(), ditched the sink
now it's working
void createFile(data) async{
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = new File(tempPath+"/"+widget.tileText);
await file.writeAsBytes(base64Decode(data));
print(await file.length());
OpenFile.open(file.path);
print(await tempDir.exists());
print(file.path);
}
Related
I am able to open and stream the file no issue by using the following, however I need to be able to use the file information that is stored inside the bucket.
const db = connection.connections[0].db
const bucket = new mongoose.mongo.GridFSBucket(db, {
bucketName: bucketName
});
bucket.openDownloadStreamByName(filename).pipe(res)
For example I would like to be able to set the following
res.setHeader('Content-Type', (TYPE)),
res.setHeader('Content-Length', (LENGTH)),
I am wondering the following above allows options however I don't know if the pipe stops us from setting the content-type and length after it starts piping.
According to docs, no you can't get file info from stream but in source code seems you can.
According to this and this, you could get contentType by accessing
bucket.openDownloadStreamByName(...).s.files[0].contentType
or
bucket.openDownloadStreamByName(...).s.file?.contentType
I've had a problem recently with users trolling and then deleting images before I can see what they are. So I'm creating a log to download everything into a log. (yes I've instantiated fs.js already). For some reason though, when writing the file... the file is only 9 bytes big (and the content is just "undefined"). Please help.
var attachment = (message.attachments).array();
attachment.forEach(function(attachment) {
console.log(attachment.url);
tempName = attachment.url.split("/");
attachName = tempName[tempName.length-1]
console.log(attachName);
fs.writeFileSync(dir + "/" + attachName, attachment.file, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log('attachment saved!');
});
theLog += '<img src="'+ "attachments/" + message.channel.name + "/" + attachName + '"> \n';
//theLog += '<img src="'+ attachment.url + '"> \n';
})
Lets start with answering why it saves it as undefined.
If you check the docs for MessageAttachment message.attachments.first().file is undefined. there is fileName and fileSize but no file
To save the file you can do 2 things...
Saving the URLS.
You can save the url in an array in a JSON file like so:
JSON FILE
{
"images":[]
}
JS FILE
let imgs = require(JSON_FILE)
imgs.images.push(attachment.url);
fs.writeFile(JSON_FILE,JSON.stringify(imgs,null,4));
- Saving the IMAGE itself
You can use the request module to pull images from a url
JS FILE
//Start of code
let request = require(`request`);
let fs = require(`fs`);
//Later
request.get(attachment.url)
.on('error', console.error)
.pipe(fs.createWriteStream(`Img-${Date.now()}`));//The "Img-${Date.now}" Guarantees Unique file names.
EDIT: request is deprecated. It's been replaced by fetch I can't confirm this code work's with fetch but the underlining principle is the same.
I ended up solving it with a tiny function. Thanks everyone (especially the guy asking what a variable was... that was super helpful)
function downloadAttachment(url, dest, hash){
console.log('initiating download of '+ url +'...');
request(url).pipe(fs.createWriteStream(dest));
}
the "hash" variable is not used right now. I was hungry and craving corned beef hash...
I'm trying to create a json file on a Apple TV device to save some data but createFile(...) always fails, returning false. I've tried with absolutePath, relativePath and path to no success. The jsonData variable is created just fine in my implementation and it works on the Simulator:
self.fileName = "MyFileTest"
self.directory = .documentDirectory
let documentsDirectory = fileManager.urls(for: self.directory, in: .userDomainMask)[0]
self.fullyQualifiedPath = documentsDirectory.appendingPathComponent(self.fileName).appendingPathExtension("json").path
do {
let jsonData = try convertObjectToData(data: dataForJson)
if !fileManager.createFile(atPath: fullyQualifiedPath, contents: jsonData as Data, attributes: nil) {
print("File Manager failed at createFile")
throw FileErrors.FileNotSaved
}
} catch {
print("Unable to create json file \(error.localizedDescription)")
throw FileErrors.FileNotSaved
}
Here createFile fails and returns false and the following is printed out:
File Manager failed at createFile Unable to create json file The
operation couldn’t be completed.
(TestAppTVOS.FileSaveHelper.(FileErrors in
_70D0A1275AC2AFFFA4ED048E3A809030) error 1.)
The fullyQualifiedPath variable value is:
/var/mobile/Containers/Data/Application/00DCB709-5EC6-40FC-BB21-D797EB4FE2F5/Documents/MyFileTest.json
Not sure what to make out of that error message "The operation couldn’t be completed" and "error 1"? Any ideas how to get this working properly for Swift 3?
After spending a bit too much time on this it seems it was related to which folder I was creating the file in.
As I am in sandbox mode/debugging I could not write to the Documents folder so instead had to switch to the Cache folder.
E.g
self.directory = .cachesDirectory
Works now.
I have a URL to the csv file and I need a code in C#.net to read the file from this url and open it in the browser..basically allow an option for save and open. I am trying to use System.Net.WebClient
Can anyone pls help on this..Thanks in advance
Haven't done that in a long time (before .net actually), but the recipe was :
//grab the csv file
var wc = new System.Net.WebClient();
var fileContent = wc.DownloadString("your url here");
// Clear and set the headers accordingly to the desired action
Response.ClearHeaders();
Response.AddHeader("Content","text/plain");
// send the data and say goodbye
Response.Write(fileContent);
Response.Flush();
Note that I'm most certainly wrong on the mime-type settings, but you should find that easily.
I have sucessfully managed to make a file upload system which basically is copying files to a specific folder and save in the database its location. Now i need help with the download part. Imagine my file location is: Files/1306242602661_file1.exe, and in my view i have this:
<g:link controller="fileManager" action="downloadFile">
Download</g:link><br>
I need help with the downloadFile controller. Could you please give me a hint about how to do this, considering my filename is a string:
String fileName = "Files/1306242602661_file1.exe"
Within your controller create an download action with following content:
def file = new File("path/to/file")
if (file.exists()) {
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=${file.name}")
response.outputStream << file.bytes
return
}
// else for err message
You can render a file. see http://grails.org/doc/2.4.x/ref/Controllers/render.html
render file: new File ("path/to/file.pdf"), fileName: 'myPdfFile.pdf'