grails display images in folder - image

I'm trying to do a Grails webapp and now I'm trying to display all images in a folder.
To do that I have the following:
def display(){
def dir = new File("/tmp/images")
def list = []
dir.eachFileRecurse() { file ->
def avatarFilePath = new File(file.path)
response.setContentType("application/jpg")
OutputStream out = response.getOutputStream();
out.write(avatarFilePath.bytes);
out.close();
}
}
So using the code above I'm displaying one image using:
<img class="thumbnail" src='${createLink(controller: "images", action: "display")}' />
Using this code, I'm displaying one image.
How do I display all images in that folder?
Do I need to build a list? A list of what? A list of outputstream?
In that case, what should I put in my gsp file?

If the images folder was inside the app structure you could just create links to the image directly. In this case I think you need a controller action that output the contents of one file, and another action that get's the list of the images and request the file content.
class MyController {
private static final File IMAGES_DIR = new File('/tmp/images')
//get the list of files, to create links in the view
def listImages() {
[images: IMAGES_DIR.listFiles()]
}
//get the content of a image
def displayImage() {
File image = new File(IMAGES_DIR.getAbsoluteFilePath() + File.separator + params.img)
if(!image.exists()) {
response.status = 404
} else {
response.setContentType("application/jpg")
OutputStream out = response.getOutputStream();
out.write(avatarFilePath.bytes);
out.close();
}
}
}
And your gsp could do something like
<g:each in="${images}" var="img">
<img class="thumbnail" src='${createLink(controller: "myController", action: "displayImage", params:[img: img.name])}' />
</g:each>
P.S: the code is not tested, may need some adjust.

Related

Set Image Source from Handler an subsequent page calls

I am setting the source for an image using a handler following this example:
Use Razor Page handler as image source.
The code looks like this:
<img src="StreamLink?handler=Thumb&filename=#thumbpath"/>
This works great for the first time the page is called.
However, there is an option to call the same page (Albumlist) again for a different year using this link:
<a class="yearlist" asp-page="/Albumlist" asp-route Section="#strYear.Key">#strYear.Value</a>
On the second call OnGetThumb is no longer executed.
Any ideas on how to set the image source for subsequent page calls?
Thanks
Th.
You need to make sure the url in src is correct.Here is a working demo:
Index.cshtml:
<a class="yearlist" asp-page="/Test2/Albumlist" Section="1">test</a>
Test2/Albumlist.cshtml:
<img src="Albumlist?handler=Thumb&filename=1" />
Test2/Albumlist.cshtml.cs:
public class AlbumlistModel : PageModel
{
public void OnGet()
{
}
public FileResult OnGetThumb(string fileName)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/imgs/"+ fileName + ".jpg");
//Read the File data into Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path);
return File(bytes, "image/png");
}
}
result:

problem rendering image in browser FileContentResult

I want to show an image from database
I have an action
public FileContentResult GetImage(string param)
{
type obj = _someRepository.GetType(param);
if (obj!= null && obj.Image!= null)
{
return File(obj.Image.ToArray(), obj.Image.MimeType);
}
return "some default image";
}
in the view I have
< img src="<%:Url.Action("GetImage","ControllerName",new { param= somevalue })%>" alt="some text"
width="100px" height="100px" />
I also have
(Html.BeginForm("actionname", "controllername", FormMethod.Post, new { enctype = "multipart/form-data" })
set.
The image data is fetched from the database But I can't see the image in the browser,
is there something that I am missing?
Here are the steps I would perform in order to isolate the problem. Start with a simple controller action which returns some hardcoded image somewhere from your harddrive:
public ActionResult GetImage(string param)
{
byte[] image = File.ReadAllBytes(#"c:\work\foo.png");
return File(image, "image/png");
}
Now navigate directly to /ControllerName/GetImage in your browser and you should see the image.
The next step is to fetch the image from the database and probably store it on your harddisk to ensure that it is a valid image:
type obj = _someRepository.GetType(param);
File.WriteAllBytes(#"c:\work\foo.png", obj.Image.ToArray());
Now checkout the generated file and see if it is valid. The last step is to ensure that the url generated in the <img> tag is the same as the one you used to test directly. Then look at FireBug's Net tab to see if the browser correctly requests the image and what does the server return.
Most probably the issue is that the byte array returned from the database is not valid image or it is empty.
As far as the form you have shown in your question, this is for uploading files, it has nothing to do with serving dynamic images from a controller action, so I don't see what relation it might have to your question.

MVC CSV File Download + Project Awesome

I'm currently using project awesome to pop a form which asks for an account number.
I take the number and generate a csv file and send it to the browser:
string billcsv = "account_ref,line1,line2,line3"
var VIRFile = File(new System.Text.UTF8Encoding().GetBytes(billcsv), "text/csv", "billfor" + accnumber+ ".csv")
return Json(VIRFile);
I would like the end user to prompted to save the csv file but cannot figure out who to.
Should I create the CSV file on disk first then pass the url to the file to the success function and use window.open(url) or is it possible to use javascript to recreate the file from the json result?
Json Result:
{"FileContents":[65,99,99,111,117,110,116,95,82,69,70,44,73,78,86,79,73,67,69,95,84,89,80,69,44,73,78,86,79,73,67,69,95,82,69,70,44,81,84,89,95,79,82,68,69,82,44,83,69,82,86,73,67,69,95,84,69,88,84,44,85,78,73,84,95,80,82,73,67,69,44,83,69,82,86,73,67,69,95,65,77,79,85,78,84,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,49,44,83,116,97,114,83,104,105,112,32,32,79,110,101,13,10,44,76,79,65,32,45,32,32,109,116,114,115,13,10,44,71,82,84,32,45,71,84,44,48,44,48,44,48,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,50,44,66,111,97,116,32,84,114,97,110,115,102,101,114,115,32,72,105,114,101,32,67,104,97,114,103,101,44,50,53,48,46,48,48,44,53,48,48,46,48,48,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,51,44,66,101,114,116,104,105,110,103,32,32,82,70,65,32,47,32,77,111,68,44,51,53,48,46,48,48,44,49,48,53,48,46,48,48,13,10],"ContentType":"text/csv","FileDownloadName":"billfor123.csv"}
First of all don't use AJAX for downloading files. Use a normal form submission or an anchor pointing to the controller action which will serve the file. And then in the controller:
public ActionResult Download(string accnumber)
{
string billcsv = "account_ref,line1,line2,line3";
var data = Encoding.UTF8.GetBytes(billcsv);
string filename = "billfor" + accnumber + ".csv";
return File(data, "text/csv", filename);
}
Now in order to invoke this action and have the user be prompted for download simply create a link:
#Html.ActionLink("Download csv", "Download", new { accnumber = "123" })
or if you are using a form:
#Html.BeginForm("Download", "SomeController")
{
#Html.TextBox("accnumber")
<input type="submit" value="Download CSV" />
}
Submitting the form using AJAX has disadvantages. You shouldn't be doing this. I would rather use #Html.BeginForm() helper to generate the form and submit the data using button event.
Hope this helps

how to display images in Grails?

I am trying to render the images from /WEB-INF/images/sps in the GSP page using the following code:
def index = {
def baseFolder = grailsAttributes.getApplicationContext().getResource("/").getFile().toString()
println baseFolder
def imagesFolder = baseFolder + '/images/sps'
println imagesFolder
def imageList1 = new File(imagesFolder).list()
println imageList1
def imageList = Arrays.asList(imageList1)
println imageList
imageList
//redirect(action:"displayImages", params:["imageList":imageList])
//render(view:"displayImages")
}
The controller is able to read the images from the fileSystem. But when I try to display them using the following code, the images are not coming.
index.gsp
<g:each in="${imageList}" var="image">
<img src="${resource(dir: 'images', file: image.filename)}" alt="Grails"/>
</g:each>
What mistake am I doing?
EDIT:
When I try with single image, it is working fine - I am able to view the image that is in the WEB-INF/images folder
<img src="${resource(dir: 'images', file: '1.jpg')}" alt="Grails"/>
And there is no HTML code thats getting generated for the loop code(above index.gsp code). Its just blank.
My requirement is to display all the image files that are on the file system folder.
It was simpler. You should return a model from an action as a Map: [imageList: imageList] for imageList to be available by name in GSP.
And yes, can you move images folder to web-app - is it OK that all the world can request your images via HTTP?
you are returning a list of File objects, where you will call the toString method of the file object which most likely returns the absoute file path of the file object.
this would give you something like this in the html source code
<img src="/app/images/c:\path\to\imagefile.png">
try calling
<img src="${resource(dir: 'images', file: image.name)}" alt="Grails"/>
and if that doesnt work, show us the html code that it produces.
In light of new knowledge, the above won't work. The return of File.list() is actually String[] where each string is a file name rather than a complete path.
Anyways, getting a look at the html source would shed light on what exactly gets printed out.
I suspect that maybe g:each doesn't support iterating over simple array types like String[], you could try converting it to a List.
def imageList = Arrays.asList(new File(imagesFolder).list())
Have you tried converting it to a list and using g:each with that?
why are you storing your images in WEB-INF/images? why not just images? i think the code ${resource(dir:'images')} would point to the latter.
You can't render images that are located under WEB-INF using the standard image tag. The images aren't web accessible. You'll need another controller that will stream the images back to the view for you. So something like this:
class AvatarController {
def show = {
def userInstance = User.get(params.id)
def avatarFilePath = new File(userInstance.avatarURL)
response.setContentType("application/png")
response.setContentLength(avatarFilePath.size().toInteger())
OutputStream out = response.getOutputStream();
out.write(avatarFilePath.bytes);
out.close();
}
}
And then to display this image:
<img src="/app/avatar/1234" />
I'll let you work out the conversion of this into your own needs. The key, however, is that you must stream the image back since it isn't web accessible in its current location.
You're better off just serving them outside of WEB-INF, however.
don't store data in WEB-INF, store your images in /web-app/images/
in your controller:
def baseFolder = servletContext.getRealPath("/")
def folder = baseFolder + '/images/' // web-app/images/
def imagesFolder = new File(folder)
def files = imagesFolder.listFiles().toList()
List<String> imageList = []
files.each {
imageList.add(it as String)
}
return imageList
3 in your view:
<g:each in="${imageList}" var="image">
<img src="${resource(dir: 'images', file: image)}" alt="Grails"/>
</g:each>

Salesforce - Is it possible to display image file from ContentVersion to custom visualforce page?

I wrote one simple Visualforce page that let user upload an image file then
save the file to ContentVersion object.
Now I want to display the saved image in my custom visualforce page. Is it even possible?
Looks like <apex:image> cannot be used. Also <img href="{!cv.contentVersion}"...> had no luck.
The real problem is I did upload the image file successfully but what is the URL to it?
I tested with random URL outside on google and I can display the image (like /../..some.jpg"). But I can't figure out what is the absolute URL for the image file that has been uploaded to contentversion.
NOTE: This is not static resource as my users may upload image to change their user image often.
Code
public with sharing class ImageUploadTestController {
public blob file { get; set; }
public String imageFilePath { get; set; }
public ContentVersion cv { get; set; }
public ImageUploadTestController() {
cv = [select id, versionData, title, pathOnClient FROM ContentVersion limit 1];
}
//fill out the inputFile field and press go. This will upload file to the server
public PageReference go() {
ContentVersion v = new ContentVersion();
v.versionData = file;
v.title = 'some title';
v.pathOnClient ='/foo.jpeg';
insert v;
return new PageReference('/' + v.id);
}
//v.id sample
//069A00000009Ux3
}//end class
Visualforce page
<apex:page controller="ImageUploadTestController">
<apex:form >
<apex:inputFile value="{!file}" />
<apex:commandbutton action="{!go}" value="go"/>
</apex:form>
<!-- none of below works!! :( -->
{!cv.title} {!cv.pathOnClient}
<apex:image value="/069A00000009Ux3" width="220" height="55"/>
</apex:page>
I don't believe its possible to serve it from content currently The format provided by ScottW works for Documents.
The other option I've done is upload a zip file containing my images to the Static Resources which can then be referenced.
This should work:
public PageReference getContent(){
String html = ApexPages.currentPage().getParameters().get('html');
PageReference redirection = null;
redirection = new PageReference('/sfc/servlet.shepherd/version/download/' + contentVersion.Id);
redirection.setRedirect(true);
return redirection;
}
Based on my experience, "thegogz"is correct - it is not currently possible to render images directly from Content. As others have indicated, rendering from Documents and/or Static Resources does work, and IMHO using Documents is preferable because you can access the URL, binary data, etc. programmatically in Apex.
The image is shown using "/servlet/servlet.FileDownload?file=" in tag by using URL attribute.
Example : <apex:image URL="/servlet/servlet.FileDownload?file={!recordId}"/>
for more information,
visit Displaying Images in a Visual Force Page
Try <apex:image URL="/servlet/servlet.FileDownload?file={!recordId}"/>

Resources