Javascript examples found on severial sites regardinf fopen is not working for me

白昼怎懂夜的黑 提交于 2019-12-04 05:57:07

问题


I am trying to read a text file that is in the same directory as my html file using javascript so that I might include the contents of the text file in my html file.

Here is the code I have to test the fopen and fread functions

<html>

<head>

</head>

<body>
<script>
   fh = fopen('my.txt', 0); // Open the file for reading.
   if(fh!=-1) // Check if the file has been successfully opened.
   {
   length = flength(fh); // Get the length of the file.
   str = fread(fh, length); // Read in the entire file.
   fclose(fh); // Close the file.

   // Display the contents of the file.
   write(str);
   } 
</script>
</body>

</html>

I've tried replacing the 'write' with document.write and still nothing.

Here are some websites that had this code as an example:

http://answers.yahoo.com/question/index?qid=20130519190823AA2lQ1W

http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm

Any help at all would be much appreciated.

THANK YOU!!!


回答1:


Javascript has no filesystem access. As it is mentioned in the second link you posted, you will need to install special plugins in order to give JS file system access.

I don't think it is the right way to accomplish whatever you are trying to do.

In order to access client's filesystem, the popular way I've seen is using Flash or Java applet or Microsoft Silverlight for that matter.

For accessing your server filesystem, you will need to run a web server which has proper permissions to access the filesystem. Then, you can make AJAX calls to the web server, which in turn will fetch the file for you.




回答2:


As Apoorv said, JavaScript has no filesystem access. But I think it is important to consider why that is. Or rather, ask yourself, would you go to a website that could access files on your machine?




回答3:


Functions like fopen is not defined in web browsers. You cannot access file system from javascript. Either have to do something like this: Question or load your files with ajax

Either way you cannot load file's from viewer's computer, only from your server. Again either way trying to load from a different server will also result in cross origin related limitations.



来源:https://stackoverflow.com/questions/19309187/javascript-examples-found-on-severial-sites-regardinf-fopen-is-not-working-for-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!