So in the following snipet everything works fine, problem is the FakeVaultDownloads folder is created inside the pictures folder in the devices storage. Is there something else I can use to create this folder inside the downloads folder? Issues is I am also downloading other file types like pdfs and txt documents and I don’t want those inside the pictures folder it doesn’t make sense those to be there, so I am trying to save them to a universal folder and not inside the pictures folder. Thanks for reading and sorry if I posted this in the wrong category any help is greatly appreciated.
let downloadedFile = await FileSystem.downloadAsync(res.data.url, `${FileSystem.documentDirectory}${res.data.name}`);
MediaLibrary.requestPermissionsAsync().then( async (res) => {
const asset = await MediaLibrary.createAssetAsync(downloadedFile.uri);
const album = await MediaLibrary.getAlbumAsync('Download');
if (album == null) {
await MediaLibrary.createAlbumAsync('Download', asset, false);
alert("File was downloaded to the Download folder ")
} else {
await MediaLibrary.addAssetsToAlbumAsync([asset], album, false);
alert("File was downloaded to the Download folder ")
}
}).catch(err => console.log("Error: ", err));
})
.catch((err) => {
console.log("Failed" , err);
alert("Response failed something is up with the server")
My SPFx webpart is working well until I try to return the result of an Graph API call. The below code is trying to get the users that have permissions to the root file library for the site the webpart is installed.
The console.log("Reached the Graph") shows up in the inspector console so I'm guessing it has something to do with the .push() I'm using to append each returned record to the response declared at the beginning of the method.
I also tried the more documented .forEach() below without success. Any Ideas?
private _loadUser(): MicrosoftGraph.Permission[] {
let response: MicrosoftGraph.Permission[];
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
let apiUrl: string = '/groups/'+this.props.group+'/drive/items/root/permissions';
client
.api(apiUrl)
.version("v1.0")
.get((error?, result?: MicrosoftGraph.Permission[], rawResponse?: any) => {
// handle the response
if(error){
console.error(error);
}
if (result) {
console.log("Reached the Graph");
for (let res of result){
response.push(res);
}
}
}
);
});
return response;
}
result.forEach(element => {
response.push(element);
console.log(element.grantedTo.user.displayName);
});
I'm struggling to redirect a user to the correct location in an ASP.NET Core middleware.
What I'm trying to archieve is an application relative redirect, so if my app runs as https://www.example.com/app any link generated should be rooted there.
E.g. ~/path should resolve to /app/path.
I tried using UrlHelperFactory, but that's MVC and needs an ActionContext, which does not exist inside a middleware.
Heres a code sample of my middleware:
app.Map(pathMatch, appMap =>
{
// [... more code ...]
appMap.Use((context, next) =>
{
var nextUrl = context.Request.Query["nextUrl"];
var applicationBase = context.Request.PathBase;
if (nextUrl == StringValues.Empty || !UrlUtil.IsLocalUrl(nextUrl[0]))
{
context.Response.Redirect(applicationBase);
}
else
{
context.Response.Redirect(applicationBase.Add(nextUrl[0]));
}
return Task.CompletedTask;
});
});
Hello I have deployed my Vue.js app to Cloudflare workers using the following commands:
wrangler generate --site
wrangler publish --env dev
This is my wrangler.toml:
account_id = "xxx"
name = "name"
type = "webpack"
workers_dev = true
[site]
bucket = "./dist"
entry-point = "workers-site"
[env.dev]
name = "name"
route = "xxx.com/*"
zone_id = "XXX"
account_id = "XXX"
The website is fine and live on "xxx.com" but when I refresh the page on any other route I get this error message:
could not find es-es/index.html in your content namespace
Or for example:
could not find category/65/index.html in your content namespace
On nginx I had to create a .htaccess, but I have no idea on how to make it work here.
This is my index.js in case it helps:
import { getAssetFromKV, mapRequestToAsset } from '#cloudflare/kv-asset-handler'
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false
addEventListener('fetch', event => {
try {
event.respondWith(handleEvent(event))
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
}),
)
}
event.respondWith(new Response('Internal Error', { status: 500 }))
}
})
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
}
}
return await getAssetFromKV(event, options)
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request)
let url = new URL(defaultAssetKey.url)
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/')
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey)
}
}
As you know, Vue.js (like many other SPA frameworks) expects that for any path that doesn't map to a specific file, the server falls back to serving the root /index.html file. Vue will then do routing in browser-side JavaScript. You mentioned that you know how to accomplish this fallback with .htaccess, but how can we do it with Workers?
Good news: In Workers, we can write code to do whatever we want!
In fact, the worker code already has a specific block of code to handle "404 not found" errors. One way to solve the problem would be to change this block of code so that instead of returning the 404 error, it returns /index.html.
The code we want to change is this part:
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
We want to change it to:
} catch (e) {
// Fall back to serving `/index.html` on errors.
return getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/index.html`, req),
})
}
That should do the trick.
However, the above solution has a slight problem: For any HTML page (other than the root), it will do two lookups, first for the specific path, and only after that will it look for /index.html as a fallback. These lookups are pretty fast, but maybe we can make things faster by being a little bit smarter and detecting HTML pages upfront based on the URL.
To do this, we want to customize the mapRequestToAsset function. You can see a hint about this in a comment in the code:
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
Let's go ahead and use it. Replace the above comment with this:
options.mapRequestToAsset = req => {
// First let's apply the default handler, which we imported from
// '#cloudflare/kv-asset-handler' at the top of the file. We do
// this because the default handler already has logic to detect
// paths that should map to HTML files, for which it appends
// `/index.html` to the path.
req = mapRequestToAsset(req)
// Now we can detect if the default handler decided to map to
// index.html in some specific directory.
if (req.url.endsWith('/index.html')) {
// Indeed. Let's change it to instead map to the root `/index.html`.
// This avoids the need to do a redundant lookup that we know will
// fail.
return new Request(`${new URL(req.url).origin}/index.html`, req)
} else {
// The default handler decided this is not an HTML page. It's probably
// an image, CSS, or JS file. Leave it as-is.
return req
}
}
Now the code detects specifically HTML requests and replaces them with the root /index.html, so there's no need to waste time looking up a file that doesn't exist only to catch the resulting error. For other kinds of files (images, JS, CSS, etc.) the code will not modify the filename.
There appears to be a built-way to do this now:
import { getAssetFromKV, serveSinglePageApp } from '#cloudflare/kv-asset-handler'
...
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })
https://github.com/cloudflare/kv-asset-handler#servesinglepageapp
I am developing a React Native project. What I am trying to do now is that I am downloading and saving the downloaded file to the device. I am using this package, https://www.npmjs.com/package/rn-fetch-blob for downloading the file.
This is my code
RNFetchBlob.config({
fileCache: true,
})
.fetch('GET', 'https://static.standard.co.uk/s3fs-public/thumbnails/image/2016/05/22/11/davidbeckham.jpg?w968', {
})
.then((res) => {
Alert.alert(res.path());
})
After download, res.path returns the path like this.
I am trying to convert it to the URI to be displayed using the Image component. I tried binding the following state object to the Image component.
{
uri: res.path()
}
It did not work. That is why as a next attempt, I am trying to convert the path into URI and display the uri. How can I do that?
Try providing the path of the file where you want to download it,
const directoryFile = RNFS.ExternalStorageDirectoryPath + "/FolderName/";
RNFS.mkdir(directoryFile);
const urlDownload = input.url;
let fileName;
fileName = "filename.zip";
let dirs = directoryFile + fileName;
RNFetchBlob.config({
// response data will be saved to this path if it has access right.
path: dirs
}).fetch("GET", urlDownload, {
//some headers ..
})
.then(res => {
console.log("The file saved to ", res.path());
//RNFS.moveFile(dirs, directoryFile + fileName); // -> uncomment this line if it still does not store at your desired path
alert("File Downloaded At Folder");
})
.catch(err => {
console.log("Error: " + err);
});