使用AJAX读取本地D盘及指定服务器路径文件报错,求解决方案
Hey there, let's work through your two AJAX file reading problems one by one—they're both rooted in browser security rules and how web servers handle file access.
1. Reading a Local D Drive File with AJAX
Browsers block direct AJAX access to local file system paths (like D:\somefile.txt) due to the same-origin policy and core security restrictions. They don't let web pages sift through your local files without explicit user permission.
Here are your valid workarounds:
- Use the File API to let users select the file: Instead of hardcoding a local path, add a file input so the user picks the file themselves. The browser will grant access once the file is selected. Example code:
<input type="file" id="localFileInput"> <script> document.getElementById('localFileInput').addEventListener('change', function(e) { const file = e.target.files[0]; const reader = new FileReader(); reader.onload = function(event) { // Access the file content via event.target.result console.log('File content:', event.target.result); }; reader.readAsText(file); // Use readAsDataURL for images/binary files }); </script> - Host the file in your web server: Move the file to your app's static resources directory (like the
myNewFolderyou mentioned) and access it via an HTTP URL instead of a local path.
2. Fixing the Server Path AJAX Error
Your mistake here is using a local file system path (D:\eclipseworkspace\...\myNewFolder) in your AJAX request. AJAX communicates with web servers over HTTP—it can't directly access the server's local file system.
Here's how to fix it:
- Map the folder to a web-accessible URL: Since
myNewFolderlives inside yourDatasetFileUploadweb app, its HTTP path will look like:
(Adjust the porthttp://localhost:8080/DatasetFileUpload/myNewFolder/your-file-name.txt8080to match your Eclipse server's port.) - Update your AJAX request to use this URL: Swap the local path for the relative or absolute HTTP URL. Example with native JS:
Or with jQuery:fetch('/DatasetFileUpload/myNewFolder/your-file-name.txt') .then(response => response.text()) .then(content => { console.log('File content:', content); }) .catch(error => { console.error('Error reading file:', error); });$.ajax({ url: '/DatasetFileUpload/myNewFolder/your-file-name.txt', type: 'GET', success: function(content) { console.log('File content:', content); }, error: function(xhr, status, error) { console.error('Error:', error); } }); - Double-check the folder structure: Ensure
myNewFolderis directly inside theDatasetFileUploadweb app root (thewtpwebapps/DatasetFileUploadfolder). If it's nested deeper, tweak the URL path to match.
Pro tip: Test the URL directly in your browser first. If it loads the file successfully, your AJAX request will work too.
内容的提问来源于stack exchange,提问作者M.S

