load method in THREE.FileLoader only gets the content of index.html - javascript

I've set up a very small browser project using create-js-app. I try to load a file called test.txt located in my src directory.
Following is the content of my main.js:
import * as THREE from 'three';
const loader = new THREE.FileLoader();
loader.load(
"test.txt",
function (data) {
console.log(data);
},
function (xhr) {
console.log(
"Loading file : " +
(xhr.loaded / xhr.total) * 100 +
"% loaded"
);
},
function (err) {
console.error(err);
}
);
When running my site in Chrome, I get the content of my index.html file instead of test.txt. I spent some time trying to understand this with no success.
I get this result no matter which file path I specify as first argument of loader.load(), I can even specify a file that is not existing.
Has anybody already faced this issue?
Thanks a lot.
Edit: I'm using Parcel as the bundler.

This issue comes down to internal details of create-js-app, and different web applications may host static resources (i.e. images and other assets that are not compiled source code) in different ways. But generally speaking, the src/ directory is not hosted/deployed/served on the website. If your application has the structure shown here then you probably want to put the .txt file into the public/ directory instead.
Requesting any file that cannot be found at the given URL might be giving you the index page instead, depending on how your site is set up by create-js-app.

I'm updating the answer above: I'm using Parcel. I fixed my project by adding this line:
url = require('test.txt')
The require function makes the browser import the txt file, and it returns the hashed url of the stored file. All I had to do next was to call
loader.load(url, ... )

Related

I want to load an in vue that has been by post request using flask and response is its path

I already have tried many methods available on StackOverflow. Most of them ask to use require.context that will load all images path and then use image path that I have got from post response.
But my problem lies here, I ask user to upload the Image then save it locally in assets folder, process the image and save output in assets folder.
This image name has to be unique, so I use uuid.uuid4() in python- which is completely random.
require.context cannot load my image path since it was not available at time when webpack was being complied, Hence the error - Cannot find module '../assets/9a5d60e2-4c2c-4fd9-a617-5dcdde4db6cc.jpg'.
<TwentyTwenty
:before="getImgUrl(resp['original'])"
:after="getImgUrl(resp['dreamed'])"
beforeLabel='Orignal'
afterLabel="Dreamed"
keyboardStep=0.01 />
getImgUrl(pet) {
var images = require.context('../assets/', false, /\.jpg$/)
return images('' + pet + ".jpg")
}
Once your Vue application is built, there is no assets folder. You cannot require / import anything that doesn't exist at bundle-time.
What you should be doing is have your Python app save the uploaded images into a location that is accessible via HTTP (eg static/uploads or as you've indicated, your Flask app root).
You then just use a plain old, regular URL to display the image in your Vue app, eg
# .env file
VUE_APP_API_BASE=http://localhost:8080
<TwentyTwenty
:before="`${apiBase}/${resp.original}.jpg`"
:after="`${apiBase}/${resp.dreamed}.jpg)`"
beforeLabel='Orignal'
afterLabel="Dreamed"
keyboardStep="0.01" />
data: () => ({
apiBase: process.env.VUA_APP_API_BASE, // get API base URL from .env
resp: {
// whatever
}
})

How do I use a downloaded svg file within my application using Tizen Web studio?

I can get an SVG file downloaded, additionally, I can display svg files as you would normally within an image tag. I do not know how to access the folder location for downloads or the wgt-private folder so I may download images to a client's watch and then use the downloaded version.
I'm sure my file is downloading as I've console logged on successful download and when I list the items in the directory the file shows up.
Placing downloads/[filename] or wgt-private/[filename] does not appear to work as these are virtual file locations however I've no idea how to access these files within the application without using the filesystem methods.
Download:
var download_obj = new tizen.DownloadRequest('someFile.svg', 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
onprogress: function(id, receivedSize, totalSize) {
console.log(id);
console.log(receivedSize);
console.log(totalSize);
},
onpaused: function(id) {
console.log(id);
},
oncanceled: function(id) {
console.log(id);
},
oncompleted: function(id, fullPath) {
console.log(id);
console.log(fullPath);
},
onfailed: function(id, error) {
console.log(id);
console.log(JSON.stringify(error));
}
});
Full path comes out as: wgt-private/someFile.svg
Doesn't display as displays a file error in the console on all attempts.
I understand that your questions relates to how to show the image downloaded with tizen.download API in html img tag.
I can see two workarounds that could help you with it:
You can use filesystem API (which you would like to avoid), BUT since 5.0 there is a method which needs no additional privileges and I hope it will match your needs - FileSystemManager.toURI(). It just gets the path to file (returned by download API) and returns the full URI, able to be used in img.
I noticed that download to non-public directories on the device, download API returns the 'hidden' path which uses virtual root, but when downloading to public directory as 'downloads', the full path is returned and it works for img as well.
If both of above is not acceptable for you, I am afraid that the only alternative is to use regular tizen.filesystem API and resolve the path from download API and then use File.toURI() function to get the path.
var link = "http://techslides.com/demos/samples/sample.jpg"
var download_obj = new tizen.DownloadRequest(link, 'wgt-private');//Hidden the actual location however this file does display when enterting the whole file location
tizen.download.start(download_obj, {
oncompleted: function(id, fullPath) {
console.log("completed " + id + " : " + fullPath);
tizen.filesystem.resolve(fullPath, (s)=>{console.log("Resovled full path: " + s.toURI())}, (e) => {console.log(e)})
},
onfailed: function(id, error) {
console.log("failed " + id);
console.log(JSON.stringify(error));
}
});
You can find the proper web sample app: new Tizen project - Sample - Mobile 4.0 - Web application - Content - Download Manager
Open index.html and replace https://www.sample-videos.com/video/mkv/720/big_buck_bunny_720p_10mb.mkv with your file address.

ajax call not working when deployed in live domain

My ajax call is working on localhost but not when i upload the files in domain. Using ajax I am searching all jpg/png files in a folder called 'images' and showing them in my webpage. The code is -
<script>
//Use ajax to load all images (jpe?g|png|gif) from a folder to a page called Gallery
//images folder should be in the same folder as the file
var folder = "../images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
// create 'img' element using JS and dynamically add image source and class
var imgSrc = document.createElement('img');
imgSrc.src= folder + val;
imgSrc.className = 'imageThumbnails';
$("#spanImage").append(imgSrc);
}
});
}
});
</script>
please change
var folder = "../images/";
to
var folder = "images/";
hope this helps.. cheers
Ok, so as you saw when you tried accessing the folder directly in your browser, your web server does not allow this, which is common on web servers. Very few people actually want visitors to be able to see a list of all files in a folder, for security reasons.
The quick and dirty way to do this would be to allow listing files in that folder, through a htaccess file, using Options +Indexes, but I strongly recommend you do not do that
Instead, I would suggest you place a file inside your images folder called index.php and have that file build you a list of files placed alongside it, in the images folder. That way you have control over which files you show and which ones you don't. The index.php file can return a simple text output, one file name per line or something like that. Then your ajax call should work as it used to.
Hope this helps!

Why doesn't Microsoft Skydrive download multiple files even though MS example shows it? (wl.download)

Summary
I am attempting to find out why the wl.download function will not download more than one file even though the Microsoft examples seem to indicate that they can.
And, the code seems to be called for each file you attempt to download, but only the one file is actually downloaded.
Details
Here are the details of how you can see this problem which I've tried in IE 11.x and Chrome 30.x
If you will kindly go to :
http://isdk.dev.live.com/dev/isdk/ISDK.aspx?category=scenarioGroup_skyDrive&index=0
You will be able to run an example app which allows you to download files from your skydrive.
Note: the app does require you to allow the app to access your skydrive.
Once you get there you'll see code that looks like this on the right side of the page:
Alter One Value: select:
You need to alter one value: Change the
select: 'single'
to
select: 'multi'
which will allow you to select numerous files to download to your computer. If you do not make that one change then you won't be able to choose more than one file in the File dialog.
Click the Run Button to Start
Next, you'll see a [Run] button to start the app (above the code sample).
Go ahead and click that button.
Pick Files For Download
After that just traverse through your skydrive files and choose more than one in a folder and click the [Open] button. At that point, you will see one of the files actually downloads, and a number of file names are displayed in the bottom (output) section of the example web page.
My Questions
Why is it that the others do not download, even though wl.download is called in the loop, just as the console.log is called in the loop?
Is this a known limitation of the browser?
Is this a known bug in skydrive API?
Is this just a bug in the example code?
The problem here is that the call to wl.download({ "path": file.id + "/content" }) stores some internal state (among other things, the file being downloaded and the current status thereof). By looping over the list of files, that state is in fact overwritten with each call. When I tried downloading three text files at once, it was always the last one that was actually downloaded and never the first two.
The difficulty here is that the downloads are executed in the traditional fashion, whereby the server adds Content-Disposition: attachment to the response headers to force the browser to download the file. Because of this, it is not possible to receive notification of any kind when the download has actually completed, meaning that you can't perform the downloads serially to get around the state problem.
One approach that I thought might work is inspired by this question. According to the documentation, we can get a download link to a file if we append /content?suppress_redirects=true to its id. Using this approach, we can set the src property of an IFrame and download the file that way. This works OK, but it will only force a download for file types that the browser can't natively display (zip files, Exe files, etc.) due to the lack of the Content-Disposition: attachment response header.
The following is what I used in the Interactive Live SDK.
WL.init({ client_id: clientId, redirect_uri: redirectUri });
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'multi'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.api({
path: file.id + "/content?suppress_redirects=true",
method: "GET"
}).then(
function (response) {
var iframe = document.createElement("iframe");
iframe.src = response.location;
iframe.style.display = "none";
document.body.appendChild(iframe);
},
function (responseFailed) {
log("Error calling API: " + responseFailed.error.message);
}
);
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
Did you try to bind some events to the WL.download() method? According to the documentation:
The WL.download method accepts only one parameter:
The required path parameter specifies the unique SkyDrive file ID of the file to download.
If the WL.download method call is unsuccessful, you can use its then method's onError parameter to report the error. In this case, the WL.download doesn't support the onSuccess and onProgress parameters. If the WL.download method call is successful, the user experience for actually downloading the files will differ based on the type of web browser in use.
Perhaps you are getting some errors in your log to identify the problem.
For me, one suggestion without having checked the documentation, I can think of the fact that you are not waiting for each download to end. Why not change your loop in such a manner that you call WL.download() only if you know no other download is currently running ( like calling the next WL.download only in the success/complete event ):
WL.download({ "path": file.id + "/content" }).then(
function (response) {
window.console && console.log("File downloaded.");
//call the next WL.download() here <!-----------------
},
function (responseFailed) {
window.console && console.log( "Error downloading file: " + responseFailed.error.message);
}
);

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

Categories

Resources