drupal 7 get file path - javascript

I have a drupal form of type file, I want to use this form to upload a photo under the default/files/backgroudimage and than I get the uploaded file path and use it as a backgroud image for some javascript file. my question is I used both $file->uri and file_create_url($file->uri)
$file = file_load($form_state['values']['Background_image']);
// // Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
for the first $url1=$file->uri; gave me this result (relative path) public://backgroundimage/image.jpg
for the second $url2=file_create_url($file->uri); gave me full path:http://localhost:8080/SiteName/sites/default/files/backgroundimage/image.jpg
In my javascript I will get the path and use it to set a backgroud image:
document.getElementById('myElement').style.backgroundImage = 'url('+myUrl+')';
question is $myUrl how it supposed to be like? is it default/files/backgroundimage/image.jpg or public://backgroundimage/image.jpg ...?

your css should be in /sites/all/themes/xxx, so you can't access images from there by
/default/files/backgroundimage/image.jpg
public://background points to /sites/default/files/ if correctly configured but you can not use uri in js
you should use a document root relative path instead:
/sites/default/files/backgroundimage/image.jpg

Related

SuiteScript 2.0 file.load method does not accept relative path of a .xml file

I have developed a Suitlet script that, in particular, loads an .xml file for further processing using the file.load method with an absolute path. I want to use a relative path, but when I do so, it won't work.
Basically, I'm providing the file.load method with the absolute path of an .xml file.
I expect the same behavior with a relative path provided instead, but it throws an error.
Both my Suitlet and .xml are in the same folder next to each other.
Forks fine:
var xmlTemplateFile = file.load({ id: 'SuiteScripts/printXml/template.xml' });
Doesn't work:
var xmlTemplateFile = file.load({ id: 'template.xml' });
Error message:
{"type":"error.SuiteScriptError","name":"RCRD_DSNT_EXIST","message":"That
record does not exist. path: template.xml
I expect file.load, provided with a relative path, to load my .xml file seamlessly.
file.load() does not accept paths relative to the current file. Not much you can do about it other than submit a feature request to NetSuite.
This should work with ./template.xml. e.g.
var xmlTemplateFile = file.load({ id: './template.xml' });

store and access image file paths when templating (from cloudinary or other service)

I’m using gulp and nunjucks to automate some basic email templating tasks.
I have a chain of tasks which can be triggered when an image is added to the images folder e.g.:
images compressed
new image name and dimensions logged to json file
json image data then used to populate template when template task is run
So far so good.
I want to be able to define a generic image file path for each template which will then concatenate to each image name (as stored in the json file). So something like:
<img src="{{data.path}}{{data.src}}" >
If I want to nominate a distinct folder to contain the images for each template generated then cloudinary requires a mandatory unique version component to be applied in the file path. So the image path can never be consistent throughout a template.
if your public ID includes folders (elements divided by '/'), the
version component is mandatory, (but you can make it shorter. )
For example:
http://res.cloudinary.com/demo/image/upload/v1312461204/sample_email/hero_image.jpg
http://res.cloudinary.com/demo/image/upload/v1312461207/sample_email/footer_image.jpg
Same folder. Different path.
So it seems I would now need to create a script/task that can log and store each distinct file path (with its unique id generated by cloudinary) for every image any time an image is uploaded or updated and then rerun the templating process to publish them.
This just seems like quite a convoluted process so if there’s an easier approach I’d love to know?
Else if that really is the required route it would great if someone could point me to an example of the kind of script that achieves something similar.
Presumably some hosting services will not have the mandatory unique key which makes life easier. I have spent some time getting to know cloudinary and it’s a free service with a lot of scope so I guess I'm reluctant to abandon ship but open to all suggestions.
Thanks
Note that the version component (e.g., v1312461204) isn't mandatory anymore for most use-cases. The URL could indeed work without it, e.g.,:
http://res.cloudinary.com/demo/image/upload/sample_email/hero_image.jpg
Having said that, it is very recommended to include the version component in the URL in cases where you'd like to update the image with a new one while keeping the exact same public ID. In that case, if you'd access the exact same URL, you might get a CDN cached version of the image, which may be the old one.
Therefore, when you upload, you can get the version value from Cloudinary's upload response, and store it in your DB, and the next time you update your image, also update the URL with the new version value.
Alternatively, you can also ask Cloudinary to invalidate the image while uploading. Note that while including the version component "busts" the cache immediately, invalidation may take a while to propagate through the CDN. For more information:
http://cloudinary.com/documentation/image_transformations#image_versions
This is the solution I came up with. It's based on adapting the generic script I use to upload images from a folder to cloudinary and now stores the updated file paths from cloudinary and generates a json data file to publish the hosted src details to a template.
I'm sure it could be a lot better semantically so welcome any revisions offered if someone stumbles on this but it seems to do the job:
// points to the config file where we are defining file paths
var path = require('./gulp.path')();
// IMAGE HOSTING
var fs = require('fs'); // !! not installed !! Not required??
var cloudinary = require('cloudinary').v2;
var uploads = {};
var dotenv = require('dotenv');
dotenv.load();
// Finds the images in a specific folder and retrurns an array
var read = require('fs-readdir-recursive');
// Set location of images
var imagesInFolder = read(path.images);
// The array that will be populated with image src data
var imgData = new Array();
(function uploadImages(){
// Loop through all images in folder and upload
for(var i = 0; i < imagesInFolder.length;i++){
cloudinary.uploader.upload(path.images + imagesInFolder[i], {folder: path.hosted_folder, use_filename: true, unique_filename: false, tags: 'basic_sample'}, function(err,image){
console.log();
console.log("** Public Id");
if (err){ console.warn(err);}
console.log("* Same image, uploaded with a custom public_id");
console.log("* "+image.public_id);
// Generate the category title for each image. The category is defined within the image name. It's the first part of the image name i.e. anything prior to a hyphen:
var title = image.public_id.substr(image.public_id.lastIndexOf('/') + 1).replace(/\.[^/.]+$/, "").replace(/-.*$/, "");
console.log("* "+title);
console.log("* "+image.url);
// Add the updated src for each image to the output array
imgData.push({
[title] : {"src" : image.url}
});
// Stringify data with no spacing so .replace regex can easily remove the unwanted curly braces
var imgDataJson = JSON.stringify(imgData, null, null);
// Remove the unwanted [] that wraps the json imgData array
var imgDataJson = imgDataJson.substring(1,imgDataJson.length-1);
// Delete unwanted braces "},{" replace with "," otherwise what is output is not valid json
var imgDataJson = imgDataJson.replace(/(},{)/g, ',');
var outputFilename = "images2-hosted.json"
// output the hosted image path data to a json file
// (A separate gulp task is then run to merge and update the new 'src' data into an existing image data json file)
fs.writeFile(path.image_data_src + outputFilename, imgDataJson, function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
});
}
})();
A gulp task is then used to merge the newly generated json to overide the existing json data file:
// COMPILE live image hosting data
var merge = require('gulp-merge-json');
gulp.task('imageData:comp', function() {
gulp
.src('src/data/images/*.json')
.pipe(merge('src/data/images.json'))
.pipe(gulp.dest('./'))
.pipe(notify({ message: 'imageData:comp task complete' }));
});

TinyMCE: How do you keep relative URLs when uploading images BUT use absolute URL when using "insert link" option?

TinyMCE version: 4.3.10
Plugin for uploading images: jbimages
I need to store the absolute path of both images and any links added to the form so that the message can be emailed. However, toggling "relative_urls" messes one of those up.
For example:
relative_urls: true
This setting results in proper links. However, any images uploaded via jbimages result in relative links, which is no good for emails. The image gets stored as "images/21312.png". That won't open in an email, since it's missing the domain prefix.
relative_urls: false
This setting results in proper image URLs when uploading via jbimages. However, all other links get prefixed with the Document Root URL. In other words, a link added as "example.org" turns into "www.example.com/example.org", where example.com is my domain root.
The ideal result is for links to be saved as absolute and not prefixed, while uploaded images get prefixed with the domain's URL.
If there is no setting to accommodate the above, are there any other plugins that allow image uploading into the body? I tried drag and drop, but that converts the image into base64 and doesn't always work correctly.
Thanks
I would look at this additional parameter:
https://www.tinymce.com/docs/configure/url-handling/#remove_script_host
Per the docs:
If this option is enabled the protocol and host part of the URLs
returned will be removed. This option is only used if the relative_urls option is set to false
If disabled, URLs will be returned in this format:
http://www.example.com/somedir/somefile.htm instead of the default
format: /somedir/somefile.htm.
The entire topic of URL manipulation is reviewed here: https://www.tinymce.com/docs/configure/url-handling/
If everything is working as you like other than the JBImages plugin I would then ask the plugin creator if there are any settings that can be changed there to address this issue.
With the help of #Michael Fromin, I solved it with a combination of his answer/comment:
I needed the following to be set:
relative_urls: true
remove_script_host: false
urlconverter_callback : 'customURLConverter'
For the customURLConverter function, I used this:
function customURLConverter(url, node, on_save, name)
{
var checkURL;
var urlPrefix;
// Get the first 7 characters of the string
checkURL = url.substring(0, 7);
// Determine if those characters are coming from the image uploader
if(checkURL === "/system")
{
// prefix the incoming URL with my domain
urlPrefix = 'https://www.example.com';
url = urlPrefix.concat(url);
}
// Return URL
return url;
}
In my use case, the URL from my upload image using jbimages is predictable, so I can check the first X characters from it. There's no reason anyone (in my site) would be linking to a URL that begins with "/system", so I can safely always assume that any URL coming in from TinyMCE that starts with "/system" is an uploaded image.
try adding in the config tinyMCE :
convert_urls : 0

pdf.js by andreasgal does not load pdf using absolute path. Works only with relative paths

I am using a javascript library to renders pdf files using a browser.
This is the one:
https://github.com/mozilla/pdf.js
I cannot get it working with absolute paths as the path to the PDF I want to display. Altough relative paths works fine.
This call does not work:
PDFView.open("D:/Projects/Empenho/Pdf1.pdf", 0);
With relative path I managed to have it working properly:
PDFView.open("https://localhost/MyPDFs/Pdf1.pdf", 0);
open() function:
function getDocument(source) {
var workerInitializedPromise, workerReadyPromise, transport;
if (!source.url)
error('Invalid parameter array, need either .data or .url');
workerInitializedPromise = new PDFJS.Promise();
workerReadyPromise = new PDFJS.Promise();
transport = new WorkerTransport(workerInitializedPromise, workerReadyPromise);
console.log(workerReadyPromise);
workerInitializedPromise.then(function transportInitialized() {
transport.fetchDocument(source);
});
return workerReadyPromise;
};
As long the system has not a good debug system nor a good documentation I can´t find out where the problem lies.
I believe there is somenthing related to the workerReadyPromise as I can print the object and see differences when using absolte x relative path.
When I use absolute path the workerReadyPromise state is that:
http://pbrd.co/10VGnuQ
Any Idea?
PS. I am not sure if this is the same case, but found this:
Loading a pdf document using absolute path
It seems that pdf.js, gets the file you specify using AJAX.
You cannot use local file paths for AJAX requests and that seems to be where you are having problems
The answer to this question explains why.

Failed To Load Resource Error

I am having trouble viewing 3 different background-image .jpg files through one thumbnailFilePath in javascript. The HTML and CSS coding does recognize all of the files correctly, but the background images will not load into a browser. Therefore, you can not view these images. On the other hand, the browser does recognize to see the javascript videocaption text and the play_icon.png image files correctly.
// JavaScript Document
$(document).ready(function(){
$('a.videoLink').each(function(){
var thumbnailFilePath = 'video/'+$(this).attr('videofile')+'.jpg';
var videoCaption = $(this).attr('videocaption');
$(this).css('background-image','url('+thumbnailFilePath+')');
$(this).html('<div class="caption">'+videoCaption+'</div><img src="../images/play_icon.png" class="play"/>');
});
});
Maybe your video directory is not located in the same directory like your javascript file with this code? Otherwise use a additional slash in front of "video", if it is in the root:
var thumbnailFilePath = '/video/'+$(this).attr('videofile')+'.jpg';
What's the value of the following attribute?
.attr('videofile')
Did you give attention to the file extension? (maybe result is: myvideofile.mpg.jpg)
The answer is that my .jpg files must have the identical file name as my HTML source code. The videofile="bruce_waltke" must have the same .jpg name. So my .jpg file was named bruce waltke.jpg with no underscore in-between. So the .jpg was initially saved as bruce waltke.jpg but it is now saved as bruce_waltke.jpg....So the image file was broken but its now fixed.

Categories

Resources