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'
Related
I'm fairly new to Dart and Flutter, and I'm having trouble to overwrite an existing assets image from a source image.
My attempt:
try {
File localFile = File('assets/images/myImage.png');
localFile.writeAsBytesSync(originFile.readAsBytesSync());
catch (e) {
log(e.toString());
}
I get:
[log] FileSystemException: Cannot open file, path = 'assets/images/myImage.png' (OS Error: No such file or directory, errno = 2)
I did define the assets folder in pubspec.yaml:
assets:
- assets/images/
Ok, so I've read somewhere that the asset file can be accessed like this:
import 'package:flutter/services.dart' show rootBundle;
final byteData = await rootBundle.load('assets/images/myImage.png');
But I don't know how to convert byteData to a File object that represents the actual file.
I think I'm missing something very basic here. Or maybe is there is a proper way to do this that has nothing to do with this approach?
Please help.
Thanks in advance!
If you want to write a file on a user device you should look here: https://flutter.dev/docs/cookbook/persistence/reading-writing-files
Shared preferences are a space in a phone where you app can write, so it's exactly what you want!
Assets are part of you app and are not meant to be modified within the app.
During a build, Flutter places assets into a special archive called
the asset bundle that apps read from at runtime. According to the flutter website
Hope this helps!
I'm creating a project of a school. I want to show the uploaded stuff by teachers to students.
But I also need to save the file in the folder which is named as faculty name. Student will be able to browse the main directory and after that he can go in the particular faculties folder.
How can I do it? Any suggestions will be appreciated.
For file upload I would start with example like in this answer. Moving files from temporary folder could be easily done by the file uploading action.
For browsing files in your case I would create an action that is able to navigate to the folder where the files are and get a list of files from that folder. Something like this
String file = application.getRealPath("/upload");
File f = new File(file);
String [] fileNames = f.list();
File [] fileObjects= f.listFiles();
for (int i = 0; i < fileObjects.length; i++) {
if(!fileObjects[i].isDirectory()){
String fname = file+fileNames[i];
out.println(fileNames[i]);
}
}
Then map this files to the JSP as links. When that link is clicked you can retrieve the actual path on the server when action is executed. What to do with the data, of course you can return stream result from the action that is used for streaming to the client browser. You can use docs examples from the Struts site or like in this example.
To navigate to the folder use parameters in GET request, that will be used to store current directory in session. You can change it if a user change the current directory from the view layer.
I am trying to copy one jpg file from one folder into another in PhoneGap. The method I used is fs.download. However I got the error that the source url is unsupported. Here are the source and destination files.
source = "/var/mobile/Applications/9483756B-8D2A-42C5-8CF7-8D76AAA8FF2C/Shift.app/iqedata/5977e2e9239649d5a7e3b8a54719679f/06e2b8896e51472789fcc27575631f94.jpg";
target = "/var/mobile/Applications/9483756B-8D2A-42C5-8CF7-8D76AAA8FF2C/Documents/memoir/5977e2e9239649d5a7e3b8a54719679f.jpg";
Can anybody help me to implement the copyto method which I think should be the correct one to use to solve this problem? I only got the full path of both source and destination.
Thanks.
You want to use the copyTo method of the FileEntry object:
http://docs.phonegap.com/en/2.6.0/cordova_file_file.md.html#FileEntry
Using copyTo method wasn't always working for me, the moveTo method worked though.
The below code, copies a file from the www folder to the /Library/LocalDatabase folder:
function copyToLocation(dbName){
console.log("Copying :"+dbName);
window.resolveLocalFileSystemURL(cordova.file.applicationDirectory+ "www/"+dbName,function (fileEntry)
{
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "Library/LocalDatabase/",function (directory)
{
fileEntry.moveTo(directory, 'new_dbname.db',function(){
console.log('DB Loaded!');
},
function()
{
console.log('Unable to load DB');
});
//},null);
},null);
}, null);
}
In my Grails application I need to create a file in current system in which I need to save information fetched from table in database. How to do this from within controller action? I don't have any idea of it.
I have created file as
File file=new File("file name.txt")
file.createNewFile();
then I have wrote values of MySQL database table fields in it as:
file<<patient.id
file<<patient.name
.
.
.
it stores data like continuous text but I want to have a .doc file in which data should get stored in table. I found Apache's POI for creating doc file but I am not getting how it works and how I should use it.
Not sure exactly what you want to store in a file but below is an example of how to easly write a String to a file using Apache-commons-io Which should be included in grails
import org.apache.commons.io.FileUtils;
class SomeController{
def writeToFile = {
def data = getSomeStringData();
def fileStore = new File("./path/to/files/ControllerOutput_${new Date()}.txt");
fileStore.createNewFile();
FileUtils.writeStringToFile(fileStore, data);
println("your file was created # {fileStore.absolutePath} and is ${fileStore.length()} bytes");
}
}
Does this help? If not, you need to explain exactly what your looking for.
This is a comment to Michael's answer (unfortunately I still don't have the reputation to reply on answers).
If you're struggling around the problem how to specifiy the relative path from within your controller's context, this might help you:
So if you have following folder you want to read/write files from/into"..
/myproject/web-app/temp/
you can access the file like this:
import org.codehaus.groovy.grails.commons.ApplicationHolder as AH
// getResource references to the web-app folder as root folder
Resource resource = AH.getApplication().getParentContext().getResource("/temp/myfile.txt)
Briefly: I can make a file, save it in the file system and then make a page with a link to that file, but what if I want a page with links to many files which may not all need to be generated?
So my user clicks a link on the list page like:
<g:link action="gimmeAFile" id="${myThingieInstance.id}">${fieldValue(bean: myThingieInstance, field: "id")}</g:link>
Right now I have a controller that looks like this:
def gimmeAFile = {
def lotsaLines = []
//Do a ton of stuff that has lotsaLines.add(resultStrings) all over
def fileName = "blahblah-${dateOrSomething}.csv"
def dumbFile = new File('web-app/tmpfiles/'+fileName).withWriter {out ->
lotsaLines.each{
out.println it
}
}
[fileName:fileName]
}
And then they go to gimmeAFile.gsp which has the link to actually download the file:
Download Report
How do I make a link on the list viewer that will create and download the file without dragging the user to an extra screen. NOTE: I cannot have the files pre-generated, so I need to figure out how to link to a file that isnt there yet. I'm thinking something like render() at the end of the controller. Can I make the gimmeAFile controller just give the file instead of making a page with a link to the file?
OK so to clarify this is what I finally figured out based on Kaleb's answer. Thankyou SO!!
def gimmeAFile = {
def lotsaLines = []
//Do a ton of stuff that has lotsaLines.add(resultStrings) all over
def fileName = "blahblah-${dateOrSomething}.csv"
def dumbFile = new File('web-app/tmpfiles/'+fileName).withWriter {out ->
lotsaLines.each{
out.println it
}
}
def openAgain = new File('web-app/tmpfiles/'+fileName)
response.setContentType("text/csv")
response.setHeader("Content-disposition", "filename=${fileName}")
response.outputStream << openAgain.getBytes()
response.outputStream.flush()
return
}
You can create a view that just gets the bytes of the file and writes out to the response:
response.contentType = 'image/jpeg' // or whatever content type your resources are
response.outputStream << file.getBytes()
response.outputStream.flush()
Is that what you're trying to do?
Another option which is a bit nicer, you can just render the file, straight from your controller's action:
render(file: theFile, contentType: 'your/contentType')
See also: http://grails.org/doc/latest/ref/Controllers/render.html
(I've found that if you add the fileName option, it prompts the user to download the file.)