In yii2 how to refer a external csv file into java script? - javascript

As it is yii2, i cannot refer external file.
my index file in view folder code is :
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"temperatures.csv", // path to CSV file
{} // options
);
</script>
i need to call my temperatures.csv in the same view folder, i don't know how to give the path, any help?

The folder with view templates is not directly accessible in yii2 so there is no way to refer the csv file there from javascript.
The most simple way to deal with it is to put the csv file in the web folder.
For example you can put your csv file to web/data folder. To get the url for the file you can use url helper.
\yii\helpers\Url::to('#web/data/temperatures.csv');
It's better to use the url manager to get the url because it will take care of handling the base url for you, that might be different in different environments. For example final url will probably be /data/temperatures.csv in production but it can be /web/data/temperatures.csv in development.
Another option is to make action that will send the file.
In that case you can leave the temperatures.csv where it is. You need to make a new action in your controller, for example getTemperatures.
public function actionGetTemperatures()
{
$file = \Yii::getAlias('#app/views/controller/temperatures.csv');
return \Yii::$app->response->sendFile($file);
}
Then you will use the url of this action in javascript.
\yii\helpers\Url::to(['controller/get-temperatures']);
The advantage of this solution is, that it allows you to control whether the user is allowed to access the file.

Related

Create and download (html/css/js) files client-side

I've built a code playground (similar to liveweave) using react. the users can save their "code playgrounds" and access them later. (using firebase db) ,this "code playgrounds"are just made of HTML, CSS, and js. I´m trying to add a functionality which allow the user to download a playground, the idea is that it will generate 3 separate files (one for each language in the playground)
1) is there a way to generate (HTML CSS and js) files and populate them with content client-side?
2) if so, would there be any chance to group those files inside a .rar also client-side?
3) if generating these files client-side is not the optimal solution/not possible, how would you approach this problem?
I was thinking maybe in an express server that queries the data from the db and then response with those files, but I would like to try a client-sided solution
Finally decided to use fileSaver.js package
import { saveAs } from "file-saver";
const saveFiles = () => {
var blob = new Blob([makeHtml(getDocumentCode())], {
type: "text/plain;charset=utf-8",
});
saveAs(blob, `${getFileName()}.html`);
};
first, you need to make a blob out of the content of the file, in this case, it was HTML +css +js code, makeHtml function handles how the HTML document is constructed, then just pass that blob to the saveAs function along the name and extension for the file, then you can use saveFiles in response to any event like onClick
<button onClick={saveFile}>Download<button/>

Android webview - how to fetch a file from external storage

I have a mobile app that wraps around the web-app, using webview.
The web-app has a button to open a large .zip file (e.g. 100 MB).
The user clicks a button, and selects a .zip file.
This triggers an onChange function with a variable of type File (Blob), which includes attributes like:
file name
file size
file type (application/zip)
The javascript code then parses the .zip file, extracts specific data within it and uses it within the web-app.
This works well within the web-app, when the app is called via the Chrome browser.
For example when operated in chrome browser on an Android phone, I can pull the .zip file and open it in the web-app.
I want to do the same but using the mobile app.
I am able to pick up the .zip file using a File Chooser, and pass it to Webview but I have problems to fetch the file from the Javascript code.
For reference, I am able to pass an image, by creating a data_uri using stringBuilder and passing the content (as data:image/jpeg;base64).
But the zip file is much larger.
When calling fetch(fileUri) from the Javascript side I'm getting errors.
I'm using the following uri
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
The fetch succeeds but returns a blob with size of 165 (i.e. not the actual size of the file) which hosts the error message:
{
"error": "Not Found",
"message": "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
}
The program flow is like so:
I select a .zip file via FileChooser.
In onActivityResult, the uri value is /document/msf:12858 (seen via uri = intent.getData();)
The uri needs to be mapped into a real path file url, such that the fileUrl will be passed to webview.
Webview will then fetch the file using the fileUrl.
I searched how to get the real path file url when selecting a file with FileChooser, and found
this, and this links.
I wasn't able to get the real file path, so I decided to read the file and write it to another location, so I can get a file path. (this is not efficient and done just to check the functionality).
I create the new file using the following code:
InputStream stream = context.getContentResolver().openInputStream(uri);
File file2 = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "file2.zip");
writeBytesToFile(stream, file2);
I don't see any errors when creating the file, and when creating the file, the number of bytes that are read and written to the new file are as expected.
For file2, I get a value of:
/storage/emulated/0/Android/data/com.example/files/Download/file2.zip
Then, within the Javascript code I fetch this file path.
But I'm getting a Blob with the "file-not-found" content as above.
So:
How can I verify that the file is indeed created and that the path can be fetched from webview?
How can I get the real file path of the original selected file, so I don't have to read and write the original file to new location just to get the file path?
Thanks
I was able to get the file from external storage by doing the following steps:
create an initial uri (uri1)
The uri is created by:
creating a temporary file (file1) in the storage dir via
context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
I'm not sure why a temporary file need to be created but if I don't create a file I cannot get the uri.
createFile3
get the uri via
Uri uri1 = FileProvider.getUriForFile(context, "com.example.android.fileprovider", file1);
create an intent with the following attributes:
Intent.ACTION_OPEN_DOCUMENT
category: Intent.CATEGORY_OPENABLE
type: "application/zip"
extra attribute: fileIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri1);
this opens a dialog box for selecting openable zip files in the Downloads directory,
after the file is selected, a new uri (uri2) is created that includes the name of the selected file.
extract the name of the file via
String fileName = getFileName(context, uri2);
create the dirPath by appending the filename
dirPath = "/data/user/0/com.example/" + fileName;
if the dirPath does not exist (first time), write the file to its dirPath location.
on successive ocassions dirPath exists, so there is no need to re-write the file.
open the file with regular Java means, e.g. via
ZipFile zip = new ZipFile(dirPath);

How can I find the current html filepage name using Javascript, on a LIVE-SERVER

I am going to deploy this page on an FTP
And I need to find out how I can detect the html file currently being viewed using JavaScript.
If I open the html file, it works just fine with this:
var fileName = location.href.substring(location.href.lastIndexOf("/") +1);
But, if I open it via my localhost adress, it has a null value. So I'm guessing I have to use some other method to extract the current html file name. Or is there a better approach to this?
Note: I am not going to use JQuery or anything like that.
EDIT:
I can get the filename if it isn't my index file.. If it's the index file I get nothing using the above code. Most likely since all I have in my adress bar is the localhost adress of the live-server?
The web deals in URLs, not file names.
Sometimes a URL will include something that looks like a file name, and sometimes that even maps on to a real file name on the server's hard disk.
When you type http://example.com/ then it might map that onto a file called index.html. Or maybe on to index.php. Or maybe it won't touch any file but will just use logic built into the web server application to determine what to respond with.
There's no way to know in the general case.
If your specific case, you know that the path / maps onto index.html, so you can write an explicit mapping in your JavaScript code.

How to serve files from express 4.0 public folder as formatted html and not files, based on extension? E.g. format JSON, show images

Hey so anytime I place something in the "public" dir of my express directory, it automatically has a link on my webpage that I like. For example, going to https://website.com/image.jpg will allow me to download an image, and https://website.com/object.json will allow me to download a JSON file, without me having to do anything aside from place these files in my public folder. This is super convenient since I have another script that could be making a bunch of different things that I won't want to specify by name on my server every time I change something.
What I would like to do is modify this serve command so that when I want to retrieve an image, instead of automatically downloading it, it displays it in the browser. This should be as simple as adding an <html> </html> around anything in the public folder that has the .png file ending. Likewise, I would like to stringify any JSON file so that it comes out in a readable format (JSON.stringify(object,null,2));
Basically, I would like to be able to just put something in my public folder and automatically be able to access it in a desirable way based on its file extension. In these two cases the "desirable" way is not downloading the file, but displaying it in-browser in a human-friendly format.
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.
app.use(express.static(path.join('.', 'public')));
Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.
var fs = require('fs');
app.use(function(req, res, next){
fileName = req.url.substring('https://website.com/'.length);
if(fs.existsSync('public/'+fileName){
if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})
As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'

jQuery get url not fixed/static

I am trying to get some xml into a html table. The thing is my xml is created dynamically on the server as a temporary document. How can I call this file if the url can be different? I hope this makes sense. I am new to jQuery, Javascript.
At the time of dynamic generation of the file on the server, also write the path of the file in a static file. Use the client to retrieve the path from the static file and then make the actual request to the dynamically generated file.
hope i understood your question right.

Categories