Image upload to filesystem in Grails - grails

I'm implementing a file upload functionality to a web-app in Grails. This includes adapting existing code to allow multiple file extensions. In the code, I've implemented a boolean to verify that the file path exists, but I'm still getting a FileNotFoundException that /hubbub/images/testcommand/photo.gif (No such file or directory)
My upload code is
def rawUpload = {
def mpf = request.getFile("photo")
if (!mpf?.empty && mpf.size < 200*1024){
def type = mpf.contentType
String[] splitType = type.split("/")
boolean exists= new File("/hubbub/images/${params.userId}")
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
} else {
tempFile = new File("/hubbub/images/${params.userId}").mkdir()
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
}
}
I'm getting the exception message at
if (exists) {
mpf.transferTo(new File("/hubbub/images/${params.userId}/picture.${splitType[1]}"))
}
So, why is this error happening, as I'm simply collatating an valid existing path as well as a valid filename and extension?

Why do you think that convertation of File object to Boolean returns existence of a file?
Try
File dir = new File("/hubbub/images/${params.userId}")
if (!dir.exists()) {
assert dir.mkdirs()
}
mpf.transferTo(new File(dir, "picture.${splitType[1]}"))

Related

How to recognize changes in log file

I'm trying to write a java program that reacts if a new entry occures in the file C:/xampp/apache/logs/access.log in order to recognize a new request to my Apache Server.
I used the following code:
public static void monitor() throws IOException {
WatchService watcher = FileSystems.getDefault().newWatchService();
File file = new File("C:/xampp/apache/logs/");
Path dir = file.toPath();
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
for (;;) {
// wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
// get file name
#SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (kind == OVERFLOW) {
continue;
} else if (kind == ENTRY_CREATE) {
System.out.println("entry created occured");
// process create event
} else if (kind == ENTRY_DELETE) {
// process delete event
} else if (kind == ENTRY_MODIFY && fileName.toString().equals("access.log")) {
System.out.println("entry modified occured");
// process modify event
}
}
// Reset the key -- this step is critical if you want to
// receive further watch events. If the key is no longer valid,
// the directory is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
But it does not recognize the change in access.log until I manually open the file. Is there something wrong with my code?
There are differents options.
There are two questions that can be kind of similiar, the only difference is that they want to check a whole direcotry instead of just a file, but you could adapt the code to detect if the modified file is the one that you want.
Watching a Directory for Changes in Java
Java detect changes in filesystem
For a specific solution I've found
http://www.rgagnon.com/javadetails/java-0490.html
This code launches a thread that checks the lastModified value of the file, if it's different from the previous one, it means that the file has been modified. I don't know if it's very efficient, check them out.

How to delete a file saved in a folder via grails?

I am saving a .pdf/.docx file when creating a entry in y grails-app. Now on the click of Delete button I want to remove that entry from DB as well as I also want to delete the .pdf/.docx file from the folder.
Note : I am saving the path of the file in my DB.
Deleting file from physical location is as simple as this -
def file = new File(/C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg/)
file.delete()
String filePath = fileDomainObject.filePath
boolean fileSuccessfullyDeleted = new File(filePath).delete()
if(fileSuccessfullyDeleted ){
fileDomainObject.delete flush:true
}
else{
flash.error = "Error in deletion."
return
}

How to get the file extension in grails?

I recently started working on grails and i want to know how to get the
extension of a file. Ex: test.txt. I want to check extension(txt)?
any clue?
Here's another way. Using a regular expression.
def fileName = 'something.ext'
def matcher = (fileName =~ /.*\.(.*)$/)
if(matcher.matches()) {
def extension = matcher[0][1]
if(extension in ['jpg', 'jpeg', 'png']) {
// Good to go
println 'ok'
} else {
println 'not ok'
}
} else {
println 'No file extension found'
}
The question asks how to get the file extension.
With groovy, the following operation will give you the file extension of any file name:
def fileName = ...
def fileExt = fileName - ~/.*(?<=\.)/
The accepted answer goes a bit further and tries to check for specific file extensions. You can use the match operator ==~ to do this as well:
assert fileName ==~ ~/.*(?<=\.)(txt|jpe?g|png)/
This assertion will work provided the file name ends with one of the supplied extensions.
Also noticed that groovy can do positive lookbehind using (<?\.)
Hope i found the answer of my Question. How to find the extension
of a file.
String fileName = "something.ext";
int a = fileName.lastIndexOf(".");
String extName = fileName.substring(a);
System.out.println(fileName.substring(a));
ArrayList<String> extList = new ArrayList<String>();
extList.add("jpg");
extList.add("jpeg");
extList.add("png");
if(extList.contains(extName))
{
System.out.println("proceed");
}
else{
System.out.println("throw exception");
}
Lsat comment at this post

Trying to delete a uploaded file from directory file system

I have a web app that uploads files to file system and show them in a list. I am trying to delete the item with a button. I know I need to get the path of the directory file to be able to delete it and I believe this is where I am stuck:
def delete = {
def doc = Document.get(params.id)
def path = Document.get(path.id)
doc.delete(path)
redirect( action:'list' )
}
error I am getting: No such property: path for class: file_down.DocumentController Possible solutions: flash
It seems to me def path = Document.get(path.id) is wrong, in that case how do we find the path of a document ?
This is my upload method where I upload the files, assign it to a specific filesize, date, and fullPath( which is the uploaded folder)
def upload() {
def file = request.getFile('file')
if(file.empty) {
flash.message = "File cannot be empty"
} else {
def documentInstance = new Document()
documentInstance.filename = file.originalFilename
documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
documentInstance.fileSize = file.getSize() / (1024 * 1024)
documentInstance.company = Company.findByName(params.company)
if (documentInstance.company == null) {
flash.message = "Company doesn't exist"
redirect (action: 'admin')
}
else {
file.transferTo(new File(documentInstance.fullPath))
documentInstance.save()
redirect (action:'list', params: ['company': params.company])
}
}
}
I think you have an error in this line:
def path = Document.get(path.id)
You try to get path.id from the path variable you are just declaring.
I'm pretty sure that you mean
def path = new File(doc.fullPath)
path.delete() // Remove the file from the file-system
doc.delete() // Remote the domain instance in DB
Alternative:
class Document {
// Add this to your Document domain
def beforeDelete = {
new File(fullPath).delete()
}
}
and then you could just do this in your controller:
def delete = {
def doc = Document.get(params.id)
doc.delete() // Delete the domain instance in DB
redirect( action:'list' )
}

Vaadin File Uploading using FileFilter

I am Using Vaadin Framework. I need to Upload Files in the format of PDF,JAR & ZIP only. I tried with this code.This code is also I got from STACK OVER FLOW.
public void uploadStarted(StartedEvent event) {
// TODO Auto-generated method stub
System.out.println("***Upload: uploadStarted()");
ArrayList<String> allowedMimeTypes = new ArrayList<String>();
allowedMimeTypes.add("application/java-archive");
allowedMimeTypes.add("application/pdf");
allowedMimeTypes.add("application/zip");
String contentType = event.getMIMEType();
boolean allowed = false;
System.out.println(":::::::::::::contentType::::::"
+ contentType);
for (int i = 0; i < allowedMimeTypes.size(); i++) {
if (contentType.equalsIgnoreCase(allowedMimeTypes.get(i))) {
allowed = true;
break;
}
}
try {
if (allowed) {
System.out.println("boolean value:::::::allowed"
+ allowed);
finalDeedUpload.setReceiver(finalDeedFileUploadHandler);
finalDeedUpload.addListener(finalDeedFileUploadHandler);
} else {
showWarningNotification(
"Error:Please Upload File in Given Format", "");
}
This is working for while uploading PDf files it's working, while uploading Zip OR Jar file and any other file it is showing NULLPOINTER EXCEPTION.
Please help me.
Vaadin has a special upload component which is easy to use. There is a whole chapter in Book of Vaadin related to this component.
https://vaadin.com/book/-/page/components.upload.html
In Vaadin 14 there is a method setAcceptedFileTypes at class Upload:
MemoryBuffer buffer = new MemoryBuffer();
Upload upload = new Upload(buffer);
upload.setAcceptedFileTypes(new String[]{"application/zip", "application/pdf", "application/java-archive"});
The method setAcceptedFileTypes sets the HTML attribute accept at the <input type="file"> element and therefore limits / filters what the application user can upload.

Resources