I'm trying to build chrome extension that can upload image from URL to any input:type.
It is 100% possible because i found one extension which implements that i want.
Link to this extension: https://chrome.google.com/webstore/detail/upload-image-from-url/eiglgndkjiabiepkliiemoabepkkhacb?hl=en
This extension finds all inputs of file type.
Then you just need to paste a link to image from remote server.
screenshot of this extension 1
screenshot of this extension 2
I need the code which can fill known input:file with image from URL.
My use case was a little different (to automate some uploading in the background), but in any case I was able to get this working like so...
content_script.js
async function createFile(url: string) : Promise<File> {
let response = await fetch(url);
let data = await response.blob();
let metadata = {
type: 'image/jpeg'
};
return new File([data], "test.jpg", metadata);
}
chrome.runtime.sendMessage({load: "true"},async function(response) {
if (response.url) {
const designFile = await createFile(response.url);
// find the file input element and trigger an upload
const input = document.querySelector('input.jsUploaderFileInput') as HTMLInputElement;
const dt = new DataTransfer();
dt.items.add(designFile);
input.files = dt.files;
const event = new Event("change", {
bubbles: !0
});
input.dispatchEvent(event)
}
});
background.js
chrome.tabs.create({url: 'https://www.somepagewithanuploadform.com'});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.load == "true") {
sendResponse({url: "https://i.stack.imgur.com/C4ndg.jpg"});
}
});
Related
I'd like to send a File (from a <input type="file"> or drop event DataTransfer) to a newly opened window with postMessage:
const win = open(...);
win.postMessage({ file }, { transfer: [file] });
The HTML spec says this about postMessage:
Posts a message to the given window. Messages can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc.), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.
However this doesn't seem to work — it throws a DataCloneError in Chrome, Safari, and Firefox. I also tried sending the file to a new worker via new Worker(), and sending a file handle from showOpenFilePicker(), both with the same result. Is it possible to send a File to another window via postMessage?
This one seems to indicate that sending file handles should work:
File System Access API: how to send a fileHandle with postMessage?
This existing question is 6 years old and doesn't mention the transfer parameter:
How to pass a File object via postMessage or any similar function
This question is relevant, but was unanswered and is 8 years old and does not use the transfer parameter:
Transfer file to webworker: DataCloneError: The object could not be cloned
const workerSrc = `
console.log('hello from worker')
self.postMessage("worker initialized");
self.onmessage = (e) => {
self.postMessage("worker received file");
console.log('got message',e)
}
`;
const workerUrl = URL.createObjectURL(
new Blob([workerSrc], { type: "application/javascript" })
);
const worker = new Worker(workerUrl);
worker.onmessage = (e) => {
console.log("message from worker:", e.data);
};
const input = document.createElement("input");
// input.textContent = "Choose file"
input.setAttribute("type", "file");
document.body.appendChild(input);
input.addEventListener("change", () => {
// const handles = await showOpenFilePicker();
// const file = handles[0];
const file = input.files[0];
// console.log("file is", file);
try {
// const win = open("http://localhost:8080/");
// win.postMessage({ example: file }, "http://localhost:8080/", [file]);
worker.postMessage({ example: file }, { transfer: [file] });
console.log("transferred", file);
} catch (err) {
const div = document.createElement("div");
div.textContent = `${err.name}: ${err.toString()}`;
document.body.appendChild(div);
console.error(err.name, err);
}
});
I want to share an image file directly to my whatsApp or add it to my whatsApp status i.e I don't want to see any other sharing option when I click on button to share any image.
Currently I am using the following code to share
import * as Sharing from 'expo-sharing';
import * as FileSystem from 'expo-file-system';
const customShare = async (image) => {
const base64result = image.split(',')[1];
try {
let filename = 'share.png'; // or some other way to generate filename
let filepath = `${FileSystem.documentDirectory}/${filename}`;
await FileSystem.writeAsStringAsync(filepath, base64result, { encoding: 'base64' });
await Sharing.shareAsync(filepath, { mimeType: 'image/gif' })
} catch (e) {
alert(e.message);
}
};
But here it is showing all sharing option to choose, is there any way to skip this step and directly open my WhatsApp
I have my own custom system that needs to create txt files in order to print cash receipts when there is a new order. I need those files to be saved locally to the computer to a specific location, but is there a way to save the file to that location without prompting the user to choose the file location? Is it possible if you create your own FileSystemFileHandle class and then pass it as a handle?
$('.save').click(function() {
saveToFile('from website');
});
async function saveToFile(content) {
const opts = {
type: 'save-file',
accepts: [
{
description: 'Text File',
extension: ['txt'],
mimeType: ['text/plain'],
}
]
}
const handle = await window.chooseFileSystemEntries(opts); // don't to that
// create custom FileSystemFileHandle and point to the file location?
const handle = FileSystemFileHandle;
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
}
This can't be done with the File System Access API, but ironically automatically triggered downloads are still a thing with the <a download> approach.
const a = document.createElement('a');
// undefined
a.download = 'example.txt';
// "example.txt"
a.href = URL.createObjectURL(new Blob(['yolo'], {type : 'text/plain'}));
// "blob:https://example.com/8d494f54-499d-4f32-bdb4-ff047e8c60af"
a.click();
// undefined
// Downloads a file `example.txt` to your Downloads folder
I'm working with the docusign api in order to get some documents from envelopes, I get all the info, but for the PDF download I get a "filebytes" string, and when trying to process it to download it, I get just a blank page (not sure if that's the expecting result since I'm using sandbox account). I'm doing all this from the client.
here's what I'm doing to process the string:
const pdfBlob = new Blob([Buffer.from(content)], {
type: 'application/pdf'
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(pdfBlob, filename);
resolve();
} else {
const tempLink = document.createElement('a');
const url = window.URL.createObjectURL(pdfBlob);
const clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
tempLink.href = url;
tempLink.target = '_blank';
tempLink.download = filename;
document.body.appendChild(tempLink);
tempLink.dispatchEvent(clickEvent);
setTimeout(() => {
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(url);
resolve();
}, 100);
}
});
Any ideas?
Here is a blog post on this topic.
The Node.js code is this (you have to do this from server):
// You would need to obtain an accessToken using your chosen auth flow
let apiClient = new ApiClient(basePath);
let config = new docusign.Configuration(apiClient);
config.addDefaultHeader('Authorization', 'Bearer ' + accessToken);
let envelopesApi = new docusign.EnvelopesApi(config);
var accountId; // accountId for your DocuSign account
var envelopeId; // envelopeId that you are working on
// produce a ZIP file with all documents including the CoC
let results1 = await envelopesApi.GetDocument(accountId, envelopeId, 'archive', null);
// produce a PDF combining all signed documents as well as the CoC
let results2 = await envelopesApi.GetDocument(accountId, envelopeId, 'combined', null);
// produce a particular document with documentId '1'
let results3 = await envelopesApi.GetDocument(accountId, envelopeId, '1', null);
//TODO - use byte array to write or send the file for your use
If your code or this code returns an empty page, please confirm that you don't get it if you use the DocuSign web app, it's possible it is empty?
Please remember encoding, this is using 64 bit encoding to get bits in the REST API.
I use the nativescript-imagepicker-plugin for a filepicker.
This returns a PHAsset.
I have to copy it to a temporary directory to upload it.
Im new in iOS, so I tried a bit:
const options = PHVideoRequestOptions.new();
options.version = PHVideoRequestOptionsVersion.Current;
PHImageManager
.defaultManager()
.requestAVAssetForVideoOptionsResultHandler(
phAsset
, options
, (avAsset, audioMix, info) => {
try {
const tempFilePath = path.join(tempFolderPath, `${Date.now()}.mp4`);
const targetURL = NSURL.fileURLWithPath(tempFilePath);
const exportSession = AVAssetExportSession.alloc(avAsset, AVAssetExportPresetPassthrough);
exportSession.outputUrl = targetURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.exportAsynchronouslyWithCompletionHandler(() => {
console.log(exportSession.status);
});
}
catch (e) {
console.log(e);
}
}
);
My code crashes without error, so I don't know where to start to debug.
I want a MP4, to show it in web too.
At the end I need a string (path) to a mp4 file to upload id with nativescript-background-http.
Your syntax seems to be wrong
const exportSession = AVAssetExportSession.alloc().initWithAssetPresetName(avAsset, AVAssetExportPresetPassthrough);
exportSession.outputURL = targetURL;