Hi I have a Chrome Extension and I would like for it to be able to read local text files.
I remember years ago, Chrome supports chrome.fileSystem. However, this has since been deprecated.
The closest thing I could get to reading any sort of file was this code below:
async function getFile(){
//Only able to read files in the extension folder.
//not allowed on local resources
var url = chrome.runtime.getURL('manifest.json');
var response = await fetch(url);
var data = await response.json();
console.log(data);
}
However, when I tried to fetch() from a url like C:\\Users\\user\\Desktop\\TestFolder\\test.txt, I would get the following error message:
Not allowed to load local resource
I have also added the "storage" permissions in my manifest.json correctly I believe.
"permissions" : [
"cookies", "tabs",
"webNavigation",
"storage",
"http://*/",
"https://*/"
]
Is there a newer version of chrome.fileSystem or any other way I could use to read a text file stored locally?
My Chrome Version is : 100.0.4896.75
Related
I'm currently having problem with displaying image from db. In my DB (Sequelize MySQL), my columns looks like this.
Database
You can see that there is path, which is showing path to file on server. (Express server using multer to upload photos).
How Am I able to show this on my frontend? I was trying everything, but I cannot figure solution.
When I open my server folder and copy path of file there, I get path like this:
Path
When I put it in chrome, I can see that image, but when I try to display it in frontend, I'm not that lucky.
Here is my function on backend to get image.
async getOneImage (req,res){
try{
const getOneImage = await CaseImage.findOne({ where: {CaseId: req.params.CaseId, id: req.params.id}});
if (getOneImage == null) {
res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.' });
}
res.send(getOneImage);
}
catch (err) {
console.log(err);
res.status(400).send({ message: 'Nepodarilo sa načítať fotografie, skúste to neskôr.'});
}
},
Maybe should I change that response to binary or? I don't understand this topic cleary as you can see.
Thank you all for help and sorry if question is not correctly formated or named.
Ok so I tried, now I have request to node server but I get response 404 cannot get... so I'm assuming that problem is somewhere in my express settings...
this.imageSrc = http://localhost:3000/${data.path}.png
this is full url.. but response is 404.
http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png
edit.
So, this is my front-end.. You can see that I'm sending response to correct path.
frontend request
Here you can see how my backend setting of express looks like.
Express
And here is response that I'm getting when I send request to backend.
Response
But I'm still not able to see image in vue. When I check I see only blank space and in console is this reply:
"GET http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png 404 (Not Found)"
And in network tab is this.
Network tab
If you have correct paths to the images in your database you simply render them with an tag. Make sure the path to the file is complete, or relative to your static assets folder.
In your case the path seems to be some mix of static/uploads/hash and the filename problem.png.
This means the full url to the file is most likely something like:
domain.com/static/uploads//.png. The domain.com part will most likely be localhost: if you are working locally. On a production server this will be your domain you are hosting your app on.
PS. your second image is a full file path on your system, this wont be visible on a server.
So you have this static folder.
If you are not already serving this static folder with express, see this explanation on how to serve a static folder.
Once you fetch your image in the frontend you will have an image object something like this:
{
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
}
Your img tag in your html file should look as follows.
<img src="http://localhost:{PORT_OF_EXPRESS_SERVER}/static/uploads/abcdefg.........png"/>
Because you're using vue.js here is an example with axios.
MyComponent.js
import axios from 'axios';
export default {
data: () => {
return {
imageUrl: ''
}
},
mounted(): async () => {
// this route here must match what you defined in your backend
const { data } = await axios.get('/image/2/5')
console.log(data);
/** {
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
} **/
// now we set the imageUrl, assuming your express port is 1337
this.imageUrl = `http://localhost:1337/${data.path}`;
}
}
MyComponent.html
<template>
<div id="my-component">
<img :src="imageUrl"/>
</div>
</template>
<script src="./MyComponent.js"></script>
I am having a CORS issue with Ionic 3 when attempting to make GET calls to an API. I am using Ionic local server, running ionic serve in the command line for live server.
Error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not
allowed access.
I tried updating ionic.config.json with proxy setting but that does not seem to be working..
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games/"
}
]
}
My Data Service
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataProvider {
headers = new Headers({'user-key': '1234567890123'});
options = new RequestOptions ({headers: this.headers});
limit: number = 50;
constructor(public http: Http) {
console.log('Hello DataProvider Provider');
}
getGames(genre, offset_num) {
let genre_id = genre;
let offset = offset_num;
return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
}
}
I am trying to make calls to this api
Request Url
https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key YOUR_KEY
Accept application/json
Primary Question
My calls are failing. How do I create proxy for this issue?
To fix this issue, please change the following lines
ionic.config.json
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games"
}
]
}
You have to remove the " / " which is at the end of of "proxyUrl".
My Data Service
return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
In the http call, the url should begin with '/games'. '/games' because ionic will proxy http://localhost:<port>/games to https://api-2445582011268.apicast.io/games
Please use the above method for external GET and POST calls in your application.
Thank you.
If you wan to use for testing in Chrome just install chrome extension
Allow control origin
Quick and easy way
To test in development environment, you can run Google Chrome in disable-web-security mode.
Steps to follow (On Windows)
Press Windows Key + R to open Run window.
Enter/input following command and press Enter key.
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Steps to follow (On Ubuntu)
Kill all the chrome.exe instances before you run/execute it.
chromium-browser --disable-web-security --user-data-dir="[some directory here]"
Before Chrome 48
chromium-browser --disable-web-security
Steps to follow (On Mac)
Run following command in terminal.
open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security
the proxy functionality expects that you're referencing the local server. in your GET request, you're still pointed at the remote API. If you change your code to this.http.get('/games/...' it should start to function as the request will go to http://localhost:8100/games..., which the "proxy" option will catch and pass on to the URL you've provided.
You may also only need to put https://api-2445582011268.apicast.io in the proxyUrl field. I think the rest of the path is passthrough.
My CORS issue got FIXED when I updated Android System Webview from the play store.
I tried Cordova-Advance-HTTP Plugin but my PUT Request was not working with Cordova-Advance-HTTP plugin.
After Updating Android System Webview I used HTTP Client plugin which I was using before. Updating Android System Webview helped me in CORS issue
```
export function getAuthHttp(http: Http, options: RequestOptions) {
console.log("token",storage.get('id_token'));
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'id_token',
tokenGetter: (() => storage.get('id_token')),
noJwtError: true,
//globalHeaders: [{'Accept': 'application/json'}],
globalHeaders: [{'Content-Type':'application/json'},{"Access-Control-Allow-Origin": "*"}],
}), http, options);
}
```
You can handle the CORS when debugging in browser by using CORS extension or by disabling the security of Chrome.
But you need to handle the CORS when you debug in app on the server side, I was consuming woo-commerce API ,so i edited it as follows->
1.Plugins->editor->woocomerceapi
right after
<?php**
header(“Access-Control-Allow-Origin: *”);
2.Update File
I've been following the Autodesk Model Derive API tutorial on
Extracting Data From a Source File and keep getting a Translation Failure when attempting to convert the uploaded source file to SVF.
I have tried .step, .sldprt, .stl and .igs files (supported file extensions here), but all seem to throw the same error message.
The request
def self.convert_to_svf(urn, key)
url = URI("https://developer.api.autodesk.com/modelderivative/v2/designdata/job")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
body = {"input": { "urn": "#{urn}", "compressedUrn": true, "rootFilename": "#{key}" }, "output": { "formats": [{ "type": "svf", "views": ["2d", "3d"] }] }}
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["authorization"] = 'Bearer ' + token
request.body = body.to_json
JSON.parse(http.request(request).read_body)
end
The response
{"type"=>"manifest", "hasThumbnail"=>"false", "status"=>"failed", "progress"=>"complete", "region"=>"US", "urn"=>"dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6aXNvcXVlLzE4Ynk4cG9pbnQ1X2dvb2R5ZWFyLmlncw", "derivatives"=>[{"name"=>"LMV Bubble", "hasThumbnail"=>"false", "status"=>"failed", "progress"=>"complete", "messages"=>[{"type"=>"error", "message"=>"Translation failure", "code"=>"TranslationWorker-InternalFailure"}], "outputType"=>"svf"}]}
I did not see an obvious issue in your code snippet, however may I know if you have uploaded the source file(s) in zip format or only the single file of the original format (say .step, .sldprt, .stl and .igs) ?
I had the practice on the relevant APIs. I tested with Inventor assembly (with sub-assemblies and parts) and AutoCAD drawing (with Xrefs). The endpoint can work well with compressedUrn = true, specifying root file, after I uploaded file package in a zip.
If compressedUrn = true, that means the source file is compressed (zip), but this applies to the composite files, i.e. a main file has some dependent files. If it is a single file which has no dependent files, upload the source file directly, then call/modelderivative/v2/designdata/job without specifying compressedUrn and
rootFilename.
If I misunderstood your question, could you provide a bit more information or a demo dataset? Note, do not post any data that is confidential to your company.
I have multiple JSON files in one directory, and I am going to build the view contents from those JSON files. The JSON files are identical in structure.
What is the correct syntax for loading multiple JSON files for use with ng-repeat? I tried with this, but it throws a permission denied error (the view is loaded via a route, if it matters. Still learning Angular...).
I use these:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
Snippet from the view:
<div ng-controller="releases">
<article ng-repeat="album in albums">
{{ album.artist }}
</article>
</div>
Controller:
myApp.controller('releases', function($scope, $http) {
$scope.albums = [];
$http.get('contents/releases/*.json')
.then(function(releases) {
$scope.albums = releases.data;
console.log($scope.albums);
});
});
The JSON files are like this:
{
"artist" : "Artist name",
"album" : "Album title",
"releaseDate" : "2015-09-16"
}
The error message is:
You don't have permission to access /mypage/angular/contents/releases/*.json on this server.
If I use an exact filename, for example $http.get('contents/releases/album.json'), I can access the data correctly. But naturally only for one JSON, instead of the 11 files I have.
In a previous site I have done with PHP, I used an identical method, and there I could access the same files with no problem. For both, I'm using WAMP server (Apache 2) as the platform.
Could it still have something to do with the Apache config? The reason I don't think it is that, is because it does work in PHP like this:
// Get release data
$releasesDataLocation = 'contents/releases/*.json';
$releasesDataFiles = glob($releasesDataLocation);
rsort($releasesDataFiles); // Rsort = newest release first, comment out to show oldest first
// Show the releases
foreach($releasesDataFiles as $releaseData) {
$release = new Release($releaseData);
$release->display();
}
Wildcard AFAIK in such URLs is not allowed. You should build a server side endpoint that should read all the files in your directory on server, concatenate and return the response to you.
For eX: you could expose a GET URL: /api/contents/releases
and server side handler of it can read the directory containing all release JSONs and return to you.
I'm trying to read data from JSON file, using the blow code:
void makeRequest(Event e){
var path='json/config.json';
var httpRequest= new HttpRequest();
httpRequest
..open('GET', path)
..onLoadEnd.listen((e)=>requestComplete(httpRequest))
..send('');
}
this worked very well when the app run as http:// .../ index.html, but gave the below error when trying to open it as file:///.../index.html
Exception: NetworkError: Failed to load 'file:///D:/DartApp/web/json/config.json'. main.dart:53makeRequest main.dart:53<anonymous closure>
Is there another way, other than httpRequest that can read JSON file from client side!
I understand I've 3 options, 2 of them only can use HttPRequest, which are:
saving the file of the server, and reading it from the server => can use HttpRequesit
saving the file on the server, and reading it from the client => can use HttpRequesit
saving the file on the client, and reading it from the client itself => CAN NOT use HTTPRequest
I'm searching for the way to do the 3rd option, which is like making off-line Android App using webview, or making off-line Chrome packaged app, i.e I do not want to use a server at all. thanks
thanks
If all you need is the data in the json file, you can just include that data in your .dart files (as a Map variable/constant, for example).
Map config = {
"displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
};
If you need the actual json, you can put in a String. Something like:
const configJson = '''
{ "displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
}
''';
The json data can be in a separate .dart file, which can be included as part of the same library (through part of ...), or imported (import 'package:mypackage/json.dart';).
If you're looking for something that you can change and the changes are persisted, you're going to need to use some sort of offline storage, which can be web storage if you're running in a browser. You can use the approach above to define inital config data, store it in web storage, and from then on read and edit it from there.
[Previous answer below, before original question was edited.]
Sorry, read "client side", thought "server side". My mistake.
If by "client side" you mean "running in a browser", and you're trying to access a json file which is on the server, then no, there isn't any other way, other than an http request. In fact, that's the only way to read any file on the server, not just json ones. (Well, I guess you could open a WebSocket and stream the content, but that doesn't seem to be a solution you're looking for.)
[Old solution below, before my mistake (server vs client) was pointed out.]
Try:
// THIS DOESN'T WORK IN A BROWSER ENVIRONMENT (aka client side)
import 'dart:io';
import 'dart:convert';
// ...
new File('json/config.json')
.readAsString()
.then((fileContents) => json.decode(fileContents))
.then((jsonData) {
// do whatever you want with the data
});
This poor example works fine in the chrome dev editor dart web app example.
Using HttpRequest.getString works fine with filename and path.
Chris has a good write for json web service stuff at
https://www.dartlang.org/articles/json-web-service/
import 'dart:html';
import 'dart:convert';
void main() {
HttpRequest.getString('json/config.json').then((myjson) {
Map data = JSON.decode(myjson);
var version = data["version"];
var element = new DivElement();
element.text = "version = $version";
document.body.children.add(element);
});
}