Ajax url GET 404 error - javascript

I'm trying Ajax on loading all pictures inside one local folder onto my html page. Code references this question. Files run on (Tomcat 8.5) server in Eclipse first and I open url in Google Chrome. Then Ajax fails according to the console:
GET /Users/jiaqni/.../WebContent/upload 404 ()
Any idea what I did wrong? Relative path "dir='upload/';" neither works. Thanks guys!
<script>
$(document).ready(function(){
console.log("Image appending...");
var dir = "/Users/jiaqni/.../WebContent/upload/";
var regexp = new RegExp("\.png|\.jpg|\.jpeg");
$.ajax({
url: dir,
success: function (data) {
//List all .png .jpg .jpeg file names in the page
console.log("Success!");
$(data).find("a").filter(function(){return regexp.test($(this).text());}).each(function(){
var filename = this.href.replace(window.location, "");
...
});
}
});
});
</script>
.htaccess was added to folder /User/.../upload/ to ensure it's browsable. And without Ajax, <img src="upload/xxx.jpeg"/> does display image in that folder.

I am guessing that the URL in question here refers to a local resource on your computer.
Unfortunately, this is not possible - usually browsers (e.g., Google Chrome) prevent you from doing so (due to privacy & security issues that may arise by allowing it).
You should put your files in your web server (e.g., Apache, ngnix, etc.) and adjust the URL of the AJAX request accordingly.
Good luck.

Related

ajax can't find url of a folder/directory (404)

I have some ajax that returns a 404 when trying to find a folder full of images that definitely exists. I tried using the solutions here but nothing worked.
var folder = "img/macro";
$.ajax({
url : folder,
success: function (data) {
// add images to html
}
});
It makes no sense because everything works perfectly locally, but when I push it up to GitHub Pages the console says that https://example.com/img/macro/ doesn't exist when you try to run that ajax. Yet I can easily just navigate to that location in the address bar with an image filename appended: https://www.example.com/img/macro/image.jpg
How do I get the ajax to find this folder of images? Is this a .htaccess problem?
The reason I'm doing this is because I have about 50 images in the folder of img/macro that are being procedurally appended into the html so that I don't have to create 50 html elements with unique file names. This way I can just dump all my images into one folder and just have ajax grab them all.

Image files not loading through jquery ajax from server cpanel

I don't know if this is a duplicate question but i have searched and couldn't found solution for this
I am newbie in cpanel and i recently uploaded my project in it. Now there is a part in my website where i am loading a folder of images through jquery ajax. Now this was working perfectly in the local server xampp but not in the server it keeps giving 404 error that means that the files not being discovered by the ajax script. For security reasons i am not going to share the links right now but i will explain the full procedure
These are the location of those folders. These scripts are in js folder. But obviously it is included in index page. anyway lets move
var svgFolder = "img/svg/";
var productImagesFolder = "img/ImagesForProducts/";
Following are the ajax scripts that i am using to load the images of these folders
$.ajax({
url: svgFolder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|svg)$/)) {
$(".svg-shapesDiv").append("<img src='" + svgFolder + val + "' id='svg-shapes' loading='lazy'>");
}
});
}
});
$.ajax({
url: productImagesFolder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|jpg)$/)) {
$("#avatarlist").append("<img style='cursor:pointer;' class='img-polaroid' src='" + productImagesFolder + val + "' loading='lazy'>");
}
});
}
});
All of this is working fine in localhost server but for some reason when i uploaded them in the cpanel it stopped working.
I tried hard coding the img tag like this
<img src='img/svg/file.svg' id='svg-shapes' loading='lazy'>
<img src='img/ImagesForProducts/file.png' id='svg-shapes' loading='lazy'>
Things i tried
And this works fine so i think that the ajax is not figuring out the address. I also tried to search the image through link in the browser like this domainname.com/img/svg/file.svg and it works fine as well. i also tried to give ajax the path like this domainname.com/img/svg/file.svg but it doesn't work. I checked the file capitalization etc but everything is correct
If this was a stupid question then i am sorry but i don't know that what i am doing wrong and i am also new to cpanel and live hosting stuff.
Based on the response to my comment it sounds as though your xampp has "indexes" enabled by default. Please see here: https://httpd.apache.org/docs/2.4/mod/mod_autoindex.html
It may be that on your shared webhosting they are disabled by default and you would need to enable them for those 2 directories. As you are using cpanel please see here: https://docs.cpanel.net/cpanel/advanced/indexes/82/ but this can also be achieve by adding a .htaccess file to the 2 folders containing Options +Indexes.
The trouble with relying on indexes this way is that different servers could potentially return slightly different html so you could find that your xampp server returns html links (your JavaScript searches for anchor tags and gets the href from there) but the shared server may not return links it may just return the file names. Also with this html being returned your JavaScript has to parse that html, search all links and extract the href. I would therefore recommend writing a php script that gathers the relevant files and returns only those in JSON format. Much easier then for the JavaScript to parse and use and you now have full control of what is returned whether it is on your xampp server or other hosting. You can call this script whatever you want and you can place it wherever you want. You could even have one script that accepts query parameters from your AJAX call and from those it know which folder to look into and what types of files it must gather from the folder. This also has the advantage of keeping all other files in those folders hidden from prying eyes.

How to Download multiple files from javascript

I am trying to use window.location.href in a loop to download multiple files
I have a table in which i can select file's, then i run a loop of selected and
try navigate to the file path to download the files.
I keep only getting the last file to download.
I think it's due to the location herf only taking action after my javascript finishes and not as the code runs.
When i have a break point on the window.location.herf it still only downloads the last file and only when i let the code run through.
Is there a better way to initiate multiple downloads from a javascript loop.
$("#btnDownload").click(function () {
var table = $('#DocuTable').DataTable();
var rows_selected = table.rows('.selected').data();
$.each(rows_selected, function (i, v) {
window.location.href = v.FilePath;
});
});
In some browsers (at least Google Chrome) support the follow:
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
JSFiddle: https://jsfiddle.net/padk08zc/
I would make use of iframes and a script to force the download of the files as Joe Enos and cmizzi have suggested.
The answer here will help with JavaScript for opening multiple iframes for each file:
Download multiple files with a single action
The answers for popular languages will help with forcing downloads if the URL is actually something that can be served correctly over the web:
PHP: How to force file download with PHP
.Net: Force download of a file on web server - ASP .NET C#
NodeJS: Download a file from NodeJS Server using Express
Ruby: Force browser to download file instead of opening it
Ensure you change the links to point to your download script and also make sure you add the appropriate security checks. You wouldn't want to allow anyone to abuse your script.
Though this looks like an old post and I stumbled on this while trying to solve a similar issue. So, just giving a solution which might help. I was able to download the files but not in the same tab. You can just replace the event handler with download which is provided below. The urls is an array of presigned S3 URLs.
The entire code looks like below:
download(urls: any) {
var self = this;
var url = urls.pop();
setTimeout(function(){
var a = document.createElement('a');
a.setAttribute('href', url);
document.body.appendChild(a);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
// a.remove();
}, 1000)
}

Wicket and AJAX : Upload file to server and show it on page

My web application is running on tomcat6 and I'm using Wicket to develop it.
What I'm trying to do is to upload image file to the server and display it on web page as soon as it will be uploaded. I'm uploading file via AJAX as described here. The file is uploaded it is stored on disk in /home/mysuser/ path. When the file is uploaded, I'm executing JavaScript in order to load that file in to HTML object with:
Wicket code:
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
target.appendJavaScript("loadOriginalImage(\""+
(UPLOAD_FOLDER + TMP_FILE_NAME1)+"\")");
}
JavaScript code:
function loadOriginalImage(image_path){
var curImg = new Image();
curImg.src = "file://"+image_path;
curImg.onload = function(){
imgHolder.appendChild(this);
}
}
The file is uploaded well, but when the JavaScript is executed, the next error appears:
Not allowed to load local resource
Then I've tried to remove "file://" from JavaScript code, as I've found that file is read from client's local folder and not from server's. But this time I've got next error:
GET http://localhost:8080/home/myuser/originalImg.jpg 404 (Not Found)
So I have two questions:
1. How I specify in JavaScript the correct path of uploaded file?
2. Is my strategy is correct to load image to web page after uploading it to server?
There are several things to consider with your approach:
escaping file names
the webserver (tomcat/wicket in this case) most likely can not serve files from some arbitrary directory
You should implement a Resource that streams the images back and mount this Resource as Alexey has pointed out.
make sure, that you only serve image files, Make sure that you disable directory traversal, otherwise someone will figure out how to read any file from the file system.
You should mount Resource to "home/myuser/${name}", read this acticle for details.
You can adjust caching with the following code (no caching in the example):
#Override
protected void setResponseHeaders(ResourceResponse data, Attributes attributes) {
data.setCacheDuration(Duration.NONE);
super.setResponseHeaders(data, attributes);
}
To allow certain extensions check these resources:
SecurePackageResourceGuard JavaDoc.
An example of usage.

XMLHttpRequest cannot load file:///. Origin null is not allowed by Access-Control-Allow-Origin [duplicate]

I'm trying to create a website that can be downloaded and run locally by launching its index file.
All the files are local, no resources are used online.
When I try to use the AJAXSLT plugin for jQuery to process an XML file with an XSL template (in sub directories), I receive the following errors:
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/data/home.xml. Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/assets/xsl/main.xsl. Origin null is not allowed by Access-Control-Allow-Origin.
The index file making the request is file:///C:/path/to/XSL%20Website/index.html while the JavaScript files used are stored in file:///C:/path/to/XSL%20Website/assets/js/.
How can I do to fix this issue?
For instances where running a local webserver is not an option, you can allow Chrome access to file:// files via a browser switch. After some digging, I found this discussion, which mentions a browser switch in opening post. Run your Chrome instance with:
chrome.exe --allow-file-access-from-files
This may be acceptable for development environments, but little else. You certainly don't want this on all the time. This still appears to be an open issue (as of Jan 2011).
See also: Problems with jQuery getJSON using local files in Chrome
Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.
It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"
Starting a webserver can be as trivial as cding into the directory the files are in and running:
python -m http.server
[Edit Thanks #alextercete, for pointing out that it has updated in Python3]
This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.
$.ajaxPrefilter( "json script", function( options ) {
options.crossDomain = true;
});
What about using the javascript FileReader function to open the local file, ie:
<input type="file" name="filename" id="filename">
<script>
$("#filename").change(function (e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function (e) {
// Get all the contents in the file
var data = e.target.result;
// other stuffss................
};
reader.readAsText(e.target.files.item(0));
}
});
</script>
Now Click Choose file button and browse to the file file:///C:/path/to/XSL%20Website/data/home.xml
Here is an applescript that will launch Chrome with the --allow-file-access-from-files switch turned on, for OSX/Chrome devs out there:
set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files.
Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).
The way I just worked around this is not to use XMLHTTPRequest at all, but include the data needed in a separate javascript file instead. (In my case I needed a binary SQLite blob to use with https://github.com/kripken/sql.js/)
I created a file called base64_data.js (and used btoa() to convert the data that I needed and insert it into a <div> so I could copy it).
var base64_data = "U1FMaXRlIGZvcm1hdCAzAAQA ...<snip lots of data> AhEHwA==";
and then included the data in the html like normal javascript:
<div id="test"></div>
<script src="base64_data.js"></script>
<script>
data = atob(base64_data);
var sqldb = new SQL.Database(data);
// Database test code from the sql.js project
var test = sqldb.exec("SELECT * FROM Genre");
document.getElementById("test").textContent = JSON.stringify(test);
</script>
I imagine it would be trivial to modify this to read JSON, maybe even XML; I'll leave that as an exercise for the reader ;)
You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
If you only need to access the files locally then you can include the exact path to the file, rather than using
../images/img.jpg
use
C:/Users/username/directoryToImg/img.jpg
The reason CORS is happening is because you are trying to traverse to another directory within a webpage, by including the direct path you are not changing directory, you are pulling from a direct location.

Categories