I have file object and I wish to grab the URL.
screenshot of file object on Chrome console
I tried to output the properties like below, but all are giving me "undefined" except type and date.
console.log("file: " + file.type);
console.dir(file.attachment.attributes);
console.dir(file.attachment.attributes.date);
console.dir(JSON.stringify(file.attachment.attributes.author));
console.dir(file.attachment.attributes.width);
Here's how the file type looks like as below.
screenshot of file type on Chrome console
Is there something wrong with how I try to read them?
My code is based on WordPress wp-plupload.js that comes with core WordPress. Yeah, I know I shouldn't edit the core codes but I was just experimenting.
UPDATE: Below is the code.
/**
* After a file is successfully uploaded, update its model.
*
* #param {plupload.Uploader} up Uploader instance.
* #param {plupload.File} file File that was uploaded.
* #param {Object} response Object with response properties.
*/
fileUploaded = function (up, file, response) {
var complete;
// Remove the "uploading" UI elements.
_.each(["file", "loaded", "size", "percent"], function (key) {
file.attachment.unset(key);
});
file.attachment.set(_.extend(response.data, { uploading: false }));
wp.media.model.Attachment.get(response.data.id, file.attachment);
complete = Uploader.queue.all(function (attachment) {
return !attachment.get("uploading");
});
if (complete) {
Uploader.queue.reset();
}
self.success(file.attachment);
};
UPDATE: I just realized the file is NOT a file object after all.
$isFile = file instanceof File;
console.log("File? " + $isFile);
I received a "File? false". It's not a blob too! But I still wonder why I can't read the object and get the URL.
Ok, I solved the problem this way. To get the file object, I need to call file.getNative() as stated here -> https://www.plupload.com/docs/v2/File
Thanks to all for your guidance, for without you I would be a lesser coder..
Related
I've gotten this IPFS info such as "/ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE" as API response.
I want to display this file(image) on my page, but I can't find out the correct solution.
How can I get the image URL from this info in react app?
Please help with my concern.
Try adding https://ipfs.io in the beginning of your ipfs info as suggested in this document https://docs.ipfs.io/concepts/what-is-ipfs/
i.e
ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE
becomes
https://ipfs.io/ipfs/QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE
If you're using js-ipfs, you can retrieve the image over IPFS, and display it:
/** Uses `URL.createObjectURL` free returned ObjectURL with `URL.RevokeObjectURL` when done with it.
*
* #param {string} cid CID you want to retrieve
* #param {string} mime mimetype of image
* #param {number} limit size limit of image in bytes
* #returns ObjectURL
*/
async function loadImgURL(cid, mime, limit) {
if (cid == "" || cid == null || cid == undefined) {
return;
}
const content = [];
for await (const chunk of ipfs.cat(cid, {length:limit})) {
content.push(chunk);
}
return URL.createObjectURL(new Blob(content, {type: mime}));
}
Then you can display it with something like:
<body>
<img id="myImage" />
<script>
async function setImage() {
// just an example, make sure to free the resulting ObjectURL when you're done with it
//
// if your CID doesn't work, try this one: Qmcm32sVsMYhURY3gqH7vSQ76492t5Rfxb3vsWCb35gVme
// that's a popular CID, which should resolve every time
document.getElementById("myImage").src = await loadImgURL("QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE", "image/png", 524288);
}
setImage();
</script>
</body>
The big advantage of this is you're using the IPFS network itself, and not relying on a public HTTP gateway (the recommended way).
You can do something like that:
tokenURI.replace("ipfs://", "https://ipfs.io/ipfs/");
One thing to note here about fetching images from IPFS that I think isn't being discussed sufficiently in these answers is that you will need to either
Run your own node of IPFS, or
Get a hosted IPFS node through a service like Infura
I have spent a little bit of time working through this in the last couple of days, and it will always come back to you having to have direct access to your own node.
There are "Gateways," which are nodes hosted by the community, and you can read more about them in the IPFS docs here: https://docs.ipfs.io/concepts/ipfs-gateway/#limitations-and-potential-workarounds
The thing with the gateways is that they are not meant to be relied upon for production sites, as you can see below. It's possible that there is some hosted node out there that somebody is giving out for free, but I doubt it, and you wouldn't want to rely on that anyways.
I think that other questions above have elaborated how you actually process the responses once you get it, but I wanted to cover this extra ground in my answer.
ipfs docs
let imgUrl = url?.slice(url.indexOf(":"),url?.lastIndexOf("/"));
let slice = url?.slice(url.lastIndexOf("/"),url?.length)
let renderURL = `https${imgUrl}.ipfs.dweb.link${slice}`;
console.log(renderURL);
I'm trying to use Cloud Code to check whether a user-submitted image is in a supported file type and not too big.
I know I need to do this verification server-side and I think I should do it with Cloud Code using beforeSave – the doc even has a specific example about data validation, but it doesn't explain how to handle files and I couldn't figure it out.
I've tried the documented method for saving files, ie.
file = fileUploadControl.files[0];
var parseFile = new Parse.File(name, file);
currentUser.set("picture", parseFile);
currentUser.save();
and in the Cloud Code,
Parse.Cloud.beforeSave(Parse.User, (request, response) => { // code here });
But 1. this still actually saves the file on my server, right? I want to check the file size first to avoid saving too many big files...
And 2. Even then, I don't know what to do in the beforeSave callback. It seems I can only access the URL of the saved image (proof that it has been uploaded), and it seems very counter-intuitive to have to do another https request to check the file size and type before deciding whether to proceed with attaching the file to the User object.
(I'm currently using remote-file-size and file-type to check the size and type of the uploaded file, but no success here either).
I also tried calling a Cloud function, but it feels like I'm not doing the right thing, and besides I'm running into the same issues.
I can call a Cloud function and pass a saved ParseFile as a parameter, and then I know how to save it to the User object from the Cloud Code using the masterkey, but as above it still involves uploading the file to the server and then re-fetching it using its URL.
Am I missing anything here?
Is there no way to do something like a beforeSave on Parse.File, and then stop the file from being saved if it doesn't meet certain criteria?
Cheers.
If you have to do something with files, parse lets you overwrite the file adapter to handle file operations.
You can indicate the file adapter to use in your ParseServer instatiation:
var FSStoreAdapter = require('./file_adapter');
var api = new ParseServer({
databaseURI: databaseUri ,
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID,
filesAdapter: fs_store_adapter, // YOUR FILE ADAPTER
masterKey: process.env.MASTER_KEY, //Add your master key here. Keep it secret!
serverURL: "https://yourUrl", // Don't forget to change to https if needed
publicServerURL: "https://yourUrl",
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
maxUploadSize: "500mb" //you will now have 500mb limit :)
});
That said, you can also specify a maxUploadSize in your instatiation as you can see in the last line.
you have to use save in background
file = ParseFile("filename", file)
file?.saveInBackground({ e ->
if (e == null) {
} else {
Toast.makeText(applicationContext, "Error: $e", Toast.LENGTH_SHORT).show()
e.printStackTrace()
Log.d("DEBUG", "file " + e.code)
}
}, { percentDone ->
Log.d("DEBUG", "file:" + percentDone!!)
})
I am doing the following:
var content = "XYZ - stuff to write to file";
Windows.Storage.DownloadsFolder.createFileAsync("myfile.txt").done(
function (newFile) {
if (newFile) {
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.deferUpdates(newFile);
// write to file
Windows.Storage.FileIO.writeTextAsync(newFile, content).done(function () {
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.CachedFileManager.completeUpdatesAsync(newFile).done(function (updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
//WinJS.log && WinJS.log("File " + newFile.name + " was saved.", "sample", "status");
} else {
//WinJS.log && WinJS.log("File " + newFile.name + " couldn't be saved.", "sample", "status");
}
});
});
} else {
// Could not access the new file
}
}
);
However, if the file already exists it crashes saying the file already exists.
How do I check to see if the file already exists and only do the create if it is not there?
Basically I know I want to write to (not append) to myfile.txt. So I need to get newFile whether it is already existing or not so I can use writeTextAsync on it.
How do I check to see if the file already exists and only do the create if it is not there?
If there is an existing file in the current folder that already has the specified desiredName, the specified CreationCollisionOption determines how Windows responds to the conflict. The enum value can be FailIfExists, GenerateUniqueName, OpenIfExists or ReplaceExisting.
Since you are accessing the DownloadsFolder, apps can't access files in the Downloads folder that they didn't create. More details about file access permission please reference this article. So you can only set the CreationCollisionOption to FailIfExists or GenerateUniqueName.
According to your description, you need a new file to write text, so you can set the option to GenerateUniqueName which will generate a new file with unique name, for example, "myfile(2).txt". Code as follows:
Windows.Storage.DownloadsFolder.createFileAsync("myfile.txt", Windows.Storage.CreationCollisionOption.generateUniqueName).done(
function (newFile) {... });
More details please reference the scenario 1 of the file access official sample.
If you just want to use the desired file name , not to generate a new one, you may add the file to the FutureAccessList and then access it later. Pay attention that the existing file must be created by same user so that you can delete and re-create a new one later. The sample code about this you can reference the scenario 7 of the official sample.
In my php file, I'm calling this jQuery plugin with
<script>$.notifications('resources/notifications.inc.php');</script>
I previously had the php file at:
resources/dashboard.notifications.php
and later moved it to what I have now, which is:
resources/notifications.inc.php
The issue I'm having is it's like caching the arguments and still showing the old notifications php file for the requestUrl. I've cleared my cookies and everything. What should I do? I have no idea where the old value is being stored.
Here's the plugin I'm calling.
$.extend({
notifications: function() {
Notifications.requestUrl = arguments[0];
console.log(Notifications.requestUrl + " and " + arguments[0]);
Notifications.interval = arguments[1] || 15000;
}
});
Finally the output I'm getting in the console. (The unexpected token in JSON is coming from the non-existent php file that it's trying to request)
See image
It appears that it was in fact being called a second time, in another file dashboard.js
How to do a Persistence storage in firefox addon sdk of JSON in a file using OS.File in OS independent way?
Like if I save the file in D:\file in windows, it wont work in linux or even on windows without drive :D.
How do I go about doing this?
To store realObject as JSON in the file MyFileName.json which is created/overwritten in the extension-data directory within the directory for the current profile, you could do something like:
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
let asJSON = JSON.stringify(realObject,null);
let file2 = openFileInPrefsExtensionData("MyFileName.json");
overwriteTextFileFromString (file2, asJSON);
/**
* Open file in Extension's extension-data directory under the pref Directory.
* This is the correct place to store files for your extension under the profile's
* directory.
*/
function openFileInPrefsExtensionData(filename) {
let fileNameList = ["extension-data","MyExtensionID"];
fileNameList.push(filename);
//This does create all directories along the way to the file,
// but the file itself is not created.
return FileUtils.getFile("ProfD", fileNameList);
}
/**
* Overwrite a file from a string.
* Currently this just overwrites, without any callback function at the end
* of the write. If the write fails, then it is reported in the console,
* but not otherwise handled.
*/
function overwriteTextFileFromString(file,data) {
overwriteTextFile(file, data, function (status) {
});
}
/**
* Overwrite a file with a string.
*/
function overwriteTextFile(nsiFile, data, flags, callback) {
//data is data you want to write to file
//if file doesnt exist it is created
// You can also optionally pass a flags parameter here. It defaults to
// FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
//PR_RDONLY 0x01 Open for reading only.
//PR_WRONLY 0x02 Open for writing only.
//PR_RDWR 0x04 Open for reading and writing.
//PR_CREATE_FILE 0x08 If the file does not exist, the file is created. If the file exists, this flag has no effect.
//PR_APPEND 0x10 The file pointer is set to the end of the file prior to each write.
//PR_TRUNCATE 0x20 If the file exists, its length is truncated to 0.
//PR_SYNC 0x40 If set, each write will wait for both the file data and file status to be physically updated.
//PR_EXCL 0x80 With PR_CREATE_FILE, if the file does not exist, the file is created. If the file already exists, no action and NULL is returned.
let args = Array.prototype.slice.call(arguments,4);
if(typeof flags == "undefined") {
//These are already the defaults.
flags = FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
}
//XXX NOTE: Flags is currently not being used. I don't recall why I disabled its use.
var ostream = FileUtils.openSafeFileOutputStream(nsiFile);
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(data);
// The last argument (the callback) is optional.
//asyncCopy automatically closes both the input and output streams upon completion.
NetUtil.asyncCopy(istream, ostream, function (status) {
if (!Components.isSuccessCode(status)) {
// Handle error!
Components.utils.reportError('error on write isSuccessCode = ' + status);
return;
}
// Data has been written to the file.
//send the status, and any other args to the callback function.
args.unshift(status);
if(typeof callback == "function" ) {
//there is a callback function..
callback.apply(callback, args);
}
});
}