path problem when using sub directories - html

I am working on a site where i have arranged my pages in directories except for the index page. My problem occurs when i use jquery to append images to a div within a section of the pages. It shows on the index page but not on other pages (which are directories). I understand why but not sure how i can fix it.
Is there a way to fix this without having to remove my other files from directories?
var $img1 = $('<img src="images/test1.jpg" />');
var $img2 = $('<img src="images/test2.jpg" />');
$('#container').append($img1, $img2);
Please note that the above code is also in a separate directory

Assuming that your images folder is located within the root directory of your website, you could just make the src attribute root-relative:
var $img1 = $('<img src="/images/test1.jpg" />');
var $img2 = $('<img src="/images/test2.jpg" />');
$('#container').append($img1, $img2);
(Note the / added to the beginning of the src attribute).
Reference:
Having links relative to root? (Apologies for any percieved self-promotion, but it was the first Google result here on Stackoverflow for my search for "root-relative url site:stackoverflow.com").

You can write the full link including domain name: var $img1 = $('<img src="http://www.yoursitename.com/images/test1.jpg" />');

Related

HTML <a> Link href Doesn't Work with "Embedded Spaces" in a "Relative Path"

I have searched everywhere I can think of and can't find a single example of an "a" href which contains a relative path on localhost with embedded spaces.
I am trying to download a json file from my localhost located at "json/test file.json". If I rename the file to "json/test-file.json" then the link works fine. I have hundreds of json files and renaming them will break other applications.
I have also tried putting quotes around 'json/test file.json' and that does not work either.
Here is a simple tag that demonstrates the problem
<a id="download_json" href="json/test%20file.json" title="Download JSON" target="new" download>Download</a>
I have already tried encodeURI but that is a waste of time. If you can just hard code the path/file as shown above for testing with nothing fancy it would be helpful and avoid distractions.
This problem must have a very simple solution, I just can't seem to put my finger on it.
Any ideas will be deeply appreciated, Thank you for your time.
Finally found the answer. Problem only with Firefox Developers Edition
function downloadJSON(filename, dataObjToWrite){
const blob = new Blob([JSON.stringify(dataObjToWrite)], { type: "text/json" });
const link = document.createElement("a");
link.download = filename;
link.href = window.URL.createObjectURL(blob);
link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");
const evt = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
link.dispatchEvent(evt);
link.remove()
};

Force file download once a site is visited

I have a simple site example.com and an external file link. I want this scenario to be implemented:
Once a user visits example.com, a file from an external link is automatically downloaded.
Mind that I don't want a user to click some link, but just an immediate file download once the site is visited. Thus <a href="link/to/file" download>Download</a> is not what I need.
Thanks in advance.
Simply create a link and click on it via js:
<script>
window.onload = function(){
var a = document.createElement("a");
a.href = "link/to/file";
a.download = true;
a.click();
};
</script>

Can I use a local file as a source in a live page?

I like to use JSFiddle when designing a new interface because I find it convenient for various tools within. I'm working on the front end of a site where I want to use a video, and unlike an image, I cant just throw it up on imgur and link to it for free instant hosting while I fiddle with the interface design.
So I want to know if I can somehow use a local file on my PC as the source for an HTML video element hosted on a live site. Obviously this is trivial to do with a web project being worked on on my Desktop, but I'm not sure it can be done on a live test.
For example this would work on a page I open from my desktop, living on my PC:
<video id="Video-Player">
<source src="../movie.mp4" type="video/mp4"/>
</video>
But I don't know whether I can do the equivalent with a page living on the web.
Here's how to allow a user to select an image from their local machine. This should get you started in the right direction.
Add a file input button in the HTML
<input type="file" id="file-btn"/>
and the corresponding handler
document.getElementById('file-btn').addEventListener('change', function(e){
readFiles(e.target.files);
})
Then the code to read the files
function readFiles(files){
files = [].slice.call(files); //turning files into a normal array
for (var file of files){
var reader = new FileReader();
reader.onload = createOnLoadHandler(file);
//there are also reader.onerror reader.onloadstart, reader.onprogress, and reader.onloadend handlers
reader.readAsDataURL(file);
}
}
Now, I've only done this with images, but this is how I read the image data.
function createOnLoadHandler(file){
console.log('reading ' + file.name + ' of type ' + file.type)
function onLoad(e){
var data = e.target.result
display(data);
}
return onLoad
}
function display(data){
var img = document.createElement('img');
img.src = data;
var context = canvas.getContext('2d')
context.clearRect(0, 0, WIDTH, HEIGHT);
context.drawImage(img, 0, 0, WIDTH, HEIGHT);
}
Here is a demo of the above code.
As a side note, if you try to read images from another domain you'll run into cross origin policy issues. I would think the same problem exists for videos as well.

PhantomJS: setContent not working when HTML has assets

This script works:
var page = require('webpage').create();
var html = '<h1>Test</h1><img>'; //works with page.setContent and page.content
//var html = '<h1>Test</h1><img src=".">'; //only works with page.content
page.setContent(html, 'http://github.com');
//page.content = html;
page.render('test.png');
phantom.exit();
but adding a src attribute to the img makes it fail silently (page.render returns false and no image is generated).
Setting page.content directly works in both cases but then relative URLs don't. The same thing happens with other tags that load a resource such as link. It doesn't matter whether the linked resource exists or not. Tested in 1.8.1 and 1.9.2.
Is this a bug or have I misunderstood the API?
You can not render webpage if it is not fully loaded.
When you are setting link or src to <img>, It will try to load image asynchronously.
So, it requires to wait for loading finished.
Try following code.
page.onLoadFinished = function(status) {
page.render('test.png');
phantom.exit();
};
page.setContent(html, 'http://github.com');

How to set name of file downloaded from browser?

I'm writing a web application that, among other things, allows users to upload files to my server. In order to prevent name clashes and to organize the files, I rename them once they are put on my server. By keeping track of the original file name I can communicate with the file's owner without them ever knowing I changed the file name on the back end. That is, until they go do download the file. In that case they're prompted to download a file with a unfamiliar name.
My question is, is there any way to specify the name of a file to be downloaded using just HTML? So a user uploads a file named 'abc.txt' and I rename it to 'xyz.txt', but when they download it I want the browser to save the file as 'abc.txt' by default. If this isn't possible with just HTML, is there any way to do it?
When they click a button to download the file, you can add the HTML5 attribute download where you can set the default filename.
That's what I did, when I created a xlsx file and the browser want to save it as zip file.
Download
Download Export
Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
if you wish to provide a default filename, but not automatic download, this seems to work.
header('Content-Disposition: inline; filename="filetodownload.jpg"');
In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.
just need to use HTML5 a tag download attribute
codepen live demo
https://codepen.io/xgqfrms/full/GyEGzG/
my screen shortcut.
update answer
whether a file is downloadable depends on the server's response config, such as Content-Type, Content-Disposition;
download file's extensions are optional, depending on the server's config, too.
'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.
'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
download blob url file
function generatorBlobVideo(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
// console.log('res =', res);
var blob = new Blob(
[xhr.response],
{'type' : type},
);
// create blob url
var urlBlob = URL.createObjectURL(blob);
dom.src = urlBlob;
// download file using `a` tag
link.href = urlBlob;
};
xhr.send();
}
(function() {
var type = 'image/png';
var url = 'https://cdn.xgqfrms.xyz/logo/icon.png';
var dom = document.querySelector('#img');
var link = document.querySelector('#img-link');
generatorBlobVideo(url, type, dom, link);
})();
https://cdn.xgqfrms.xyz/HTML5/Blob/index.html
refs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers
Sometimes #Mephiztopheles answer won't work on blob storages and some browsers.
For this you need to use a custom function to convert the file to blob and download it
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
}
Same code as #Hillkim Henry but with a.remove() improvement
This forces the document to remove the a tag from the body and avoid multiple elements
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
// Remove "a" tag from the body
a.remove()
}
Well, #Palantir's answer is, for me, the most correct way!
If you plan to use that with multiple files, then i suggest you to use (or make one) PHP Download Manager.
BUT, if you want to make that to one or two files, I will suggest you the mod_rewrite option:
You have to create or edit your .htaccess file on htdocs folder and add this:
RewriteEngine on
RewriteRule ^abc\.txt$ xyz.txt
With this code, users will download xyz.txt data with the name abc.txt
NOTE: Verify if you have already the "RewriteEngine on " on your file, if yes, add only the second for each file you wish to redirect.
Good Luck ;)
(Sorry for my english)