Scalatra link image file outside application - scalatra

I can't seem to figure out how to display a file in a view that is located outside of the .war file. In the application I am working on I have a folder of images that is volatile at '/path/to/images/'. I am trying to link the file 'myfile.jpg' inside an img tag. In my view (scaml) I have the following code:
-val path = "/path/to/images/" + filename
%img(src = path)
This renders the following img tag
<img src="/path/to/images/myfile.jpg"/>
Scalatra resolves the src url to this invalid url
http://localhost/path/to/images/myfile.jpg
I'm kind of stuck. Can anyone point me in the right direction? I cannot store these images within /src/main/webapp/img
Many thanks,
AH

Related

flask image not displaying using img tag [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 1 year ago.
I am trying to display an image that is not in static folder but inside a logos folder.
The folder where my app.py is situated is this
app.py
static
logos <--- I want to access image from this folder.
{% for company in companies %}
{% if company.logo %}
<img src="/logos/{{company.logo}}" width="200" height="85"/>
{% endif %}
{% endfor%}
In HTML inspect element it comes properly as
<img src="/logos/59a94931df425f3034d2.jpg" width="200" height="85">
The file actually exists but the image is not displayed in webpage
The logos directory must be inside the static directory, in order to allow python to find the image and return that to the browser. In fact, if you check the console, you will see error 404: Not Found
So, put logos directory inside static and replace the url with:
src="logos/logos/{{company.logo}}.jpg"
Another way could be using url_for function (always inside your html file):
{{url_for('static', filename = f'logos/{company.logo}')}}
Let me know if it works.
Essentially what barbax has said, but your images to be rendered need to be within a static folder, and give this as the root directory when providing the path in html, e.g if this is your folder structure:
<ROOT>
└── app
└── static
└── logos
This should be your src value:
src='static/logos/{{ company.logo }}'

How to set the default directory for wysisyg editor insertImage in flask

I'm building a CMS in flask and I have built a simple wysiwyg editor using execcommands for creating and editing posts, and everything is working. For the insertImage command I'm using an input element to open a directory and choose an image. It works except of course it opens my computers default folder. I want it to open the uploads folder in the static directory where user images are stored in flask. How?
I have searched through flask docs, Python handling files documentation and there's no mention of this. This is a project I'm doing for a class. I'm going above and beyond the requirements for this project but that's how I keep things interesting. I mean it's supposed to be a CMS right. Well, CMS's always have wysiwyg's that open the default "uploads" folder to insert media. Also, when creating my upload functions I found that when uploading files flask needs the absolute path. But when serving them the relative path is necessary.
Any point in the right direction would be greatly appreciated. Thank you.
Here's the structure
<div class="col-md-1 tools">
<a href="#" data-command='insertImage'data-toggle="tooltip" title="Insert Media"><i class='material-icons'>add_photo_alternate</i>
</a>
<div class="editorInputs">
<input type="file" name="media" id="insertImage"
accept="audio/*,video/*,image/*"/>
</div>
</div>
Here's my js script
$('.tools a').mousedown(function(e){
let command = $(this).data('command');
if(command == 'insertImage'){
$(this).next().children('input').trigger('click');
let input = $(this).next().children();
input.on('change', function(e){
let val = $(input).val();
document.execCommand(command, false, val);
})
}
});
Here's how my uploads file is configured in flask
app.config['SITE_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/site/uploads/'
app.config['ADMIN_UPLOADS'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/static/admin/uploads/'
app.config['ALLOWED_IMAGE_EXTENSIONS'] = ['PNG', 'JPG', 'JPEG', 'SVG', 'GIF']
app.config['DATA_FILES'] = 'D:/Courses/Development/Programming/Python/LaunchCode/LC101/unit2/build-a-blog/data/'
app.config['RELATIVE_PATH_SITE'] = '../static/site/uploads/'
app.config['RELATIVE_PATH_ADMIN'] = '/static/admin/uploads/'
So, I realized that I have to create a function to pull images from the uploads folder, display them, get their URL and pass it to the execcommand. And I did.
First, create the gallery structure with radio buttons to view files. Then put the gallery in a bootstrap modal to fire when the execccomand insertImage link is clicked. Grab the URL of the checked image. pass it to the execcomand function in my js.
On the flask side get a list of all files in the uploads directory with os.listdir(absolute/path/to/directory), returns a python list of the files. Next create file urls and put info in a dict by looping over the filenames in the list and adding the relative path to the filename. Pass the dict to the jinja2 template and populate the gallery.
Finally, execute the js.
Here's my python code and js code.
def get_uploads():
list_images = os.listdir(app.config['ADMIN_UPLOADS'])
images = []
i =0
length = len(list_images)
while i < length:
img = {}
img['name'] = list_images[i]
img['url'] = os.path.join(app.config['RELATIVE_PATH_ADMIN'], list_images[i])
images.append(img)
i+=1
return images
Here's my js.
if(command == 'insertImage'){
$("#uploadsGallery").modal();
$('.ftco-animate').addClass('fadeInUp ftco-animated')
let check = $(this).next().find('input.form-check-input');
let val;
check.on('change', function(e){
val = $(this).val();
});
$('#insertImg').click(function (e) {
r.setStart(editDiv, lastCaretPos);
r.setEnd(editDiv, lastCaretPos);
s.removeAllRanges();
s.addRange(r);
document.execCommand(command, false, val);
check.prop('checked', false);
});
}

The joined path (relative path) is located outside of the base path component (full path)

I am trying to use thumbnail packages to generate thumbnail images from base images. Originally, I had my source images in my static dir, and as the thumbnail packages want to generate them to my media dir, I thought that was the cause of the SuspiciousFileOperation error I was getting.
No problem, I just copied my images to my media dir, which I thought would solve the issue, but no, the issue remains.
From what I can tell, it seems to be a problem with having a relative path vs a full path?
The full error is:
SuspiciousFileOperation at /toys/
The joined path (/media/images/test.jpg) is located outside of the base path component (/home/username/django/first_webapp/my_site/media)
The path /home/username/django/first_webapp/my_site/media/images/test.jpg is valid and test.jpg is a valid jpg image.
The abridged code I am using in my template, with sorl-thumbnail (although I have also tried with easy_thumbnails) is:
{% for instance in prods %}
<img src=" {% thumbnail instance.image_url 300x300 %} ">
{% endfor %}
instance.image_url, in this case, is set to /media/images/test.jpg
My media directory settings from my settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I am unsure where to begin to troubleshoot this.
I can't really understand how you think the type of the field is not relevant. Of course it is.
In your case, you have (for some reason) used a TextField to store the path of your image file. TextFields have no special knowledge of media files, and sort-thumbnail just treats the contents as a path component, which it then joins with MEDIA_ROOT. But since your path begins with a leading slash, the result of os.path.join(MEDIA_ROOT, path) is just path; the leading slash means exactly "start from the filesystem root". So the result is a path outside your project, which Django disallows for security reasons.
A quick fix is to remove the leading slash - as well as the duplicate "media" prefix - and just store "images/test.jpg". But the real fix is to use the appropriate field for the content you are storing, and let that field manage it for you.
For anyone who lands here off Google because upgrading their Django and easy-thumbnails caused the same error to start happening, check that your template is referencing your ImageField as {{image_field|thumbnail_url:'default'}}, not {{image_field.url|thumbnail_url:'default'}}.
Apparently it got less forgiving of that mistake.

Ionic2: From one of the pages, what is the proper `src` URL to display an image?

From one of the pages, what is the proper src URL to display an image located in www/assets/images/image.jpg?
<!-- Invalid Path -->
<ion-img width="80" height="80" src="assets/images/image.jpg"></ion-img>
Use path:
src="./assets/images/image.jpg
It needs to be relative
It will be assets/images/image.jpg.
I would recommend you to put you images in src folder since when you build app it will be copied into www folder.

display static html asset in jekyll + github pages

I want to add a link to a static html page (which I have created, not hosted anywhere). I added the html file to my images folder (contains the images which are being rendered in my jekyll blog). Then I make a hyperlink to the html files which I just added in the images folder, like this:
<a href=https://raw.githubusercontent.com/USERNAME/USERNAME.github.io/master/images/time.vs.score.html>View plots here</a>
Where username is my github username. This does not open a new html page, instead I just see the plain text of the html file. How can I add static html files are part of the assets? Thanks!
Thats what raw.githubusercontent.com is made returning raw file.Files are returned with Content-Type:text/plain; and then displayed as text by your browser.
You'd better link to github pages published content at https://USERNAME.github.io/images/time.vs.score.html
I found an easy solution using this tool: https://rawgit.com/
just replace:
<a href=https://raw.githubusercontent.com/USERNAME/USERNAME.github.io/master/images/time.vs.score.html>View plots here</a>
with:
<a href=https://cdn.rawgit.com/USERNAME/USERNAME.github.io/master/images/time.vs.score.html>View plots here</a>