This question already has an answer here:
Google chrome rehost image extension
(1 answer)
Closed 9 years ago.
I'm writing a Chrome Extension that automates downloading a file from one location and then uploading it to another. I've figured out how to do the download part using the HTML5 Filesystem API. However, I don't know how to then upload the file.
The issue is that the upload has to be done through a form using a "file" input element. I'd like to just tell the form where the file is located (I can get the location of the downloaded file from the Filesystem API). But I can't figure out a way of doing that programmatically.
Any ideas? Let me know if I can clarify anything!
EDIT: Another option is chrome.downloads extension API
EDIT: The File API looks promising (http://dev.w3.org/2006/webapi/FileAPI/). I also found this helpful: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
So, this is the way I finally got it working. It's done in a Chrome extension. I don't think it's possible in a normal browser script, since the canvas.toDataURL function is used and will throw a security exception if the downloaded file is cross-origin. Anyway, here's a simplified version of how I did it. Luckily the files I'm downloading and uploading are images, so I can use the Image() class.
// load the image
var img = new Image();
img.src = "url to image";
// loaded
img.onload = function() {
// convert the image into a data url
var dataUrl = getImageDataUrl(this);
var blob = dataUrlToBlob(dataUrl);
// FormData will encapsulate the form, and understands blobs
var formData = new FormData();
// "image_name.png" can be whatever you want; it's what the
// host will see as the filename for this image (the host server
// that receives the posted form). it doesn't have to match the
// original filename, and can be arbitrary or not provided at all.
formData.append("file", blob, "image_name.png");
var request = new XMLHttpRequest();
// upload
request.open("POST", "url to form");
request.send(formData);
};
// converts an image into a dataurl
function getImageDataUrl(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// NOTE: this will throw a cross-origin security exception
// if not done in an extension and if the image is cross-origin
return canvas.toDataURL("image/png");
}
// converts a dataurl into a blob
function dataUrlToBlob(dataUrl) {
var binary = atob(dataUrl.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
I donĀ“t know if something like that exists, but you could dynamically create a form using Javascript, then updating the file input value and finally trigger the form's submit event.
Related
I've tried using document.execCommand('copy') like this site but it didn't work (nothing got copied to my clipboard despite the fact that the console.log said it was successful). I also used the navigator.clipboard API but that didn't work for my jpg images, and here is its code:
navigator.clipboard.write(
[
new ClipboardItem({
'image/jpeg': new Blob( ['media/anime_0.jpg'],{type:'image/jpeg'} )
})
])
.then(e=>{console.log('Copied to clipboard')})
.catch(e=>{console.log(e)})
The above code produces the following error:
DOMException: Sanitized MIME type image/jpeg not supported on write.
Anyone know if I'm doing anything wrong or if it's even possible to copy images to clipboard without using external libraries?
Thanks Keith for the link to: convert image into blob using javascript
This is the solution I used for my app (it will only save images as png, as jpeg/jpg files keep giving me the DOMException error.
const img = new Image
const c = document.createElement('canvas')
const ctx = c.getContext('2d')
function setCanvasImage(path,func){
img.onload = function(){
c.width = this.naturalWidth
c.height = this.naturalHeight
ctx.drawImage(this,0,0)
c.toBlob(blob=>{
func(blob)
},'image/png')
}
img.src = path
}
setCanvasImage('media/anime_0.jpg',(imgBlob)=>{
console.log('doing it!')
navigator.clipboard.write(
[
new ClipboardItem({'image/png': imgBlob})
]
)
.then(e=>{console.log('Image copied to clipboard')})
.catch(e=>{console.log(e)})
})
I am trying to save image canvas to disk as .png in chrome extension with file name reflecting MD5 hash. For this I use something like this:
var img = document.createElement("img");
img.src=canvas.toDataURL("image/png");
var image_data = atob(img.src.split(',')[1]);
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i);
}
var blob = new Blob([view], {type: 'image/png'});
var url = (window.webkitURL || window.URL).createObjectURL(blob);
var b = new FileReader;
b.readAsDataURL(blob);
b.onloadend = function () {
filename = SparkMD5.hash(b.result);
}
// ....some code
chrome.downloads.download ({ url, filename+'.png', saveAs: false });
The file is saved correctly, but MD5 hash that I get in code via SparkMD5 is different from the one I see in Windows after the file is saved. I cannot understand why. Experimented a bit with different approaches to saving (directly XMLHttpRequest, etc), but no luck yet. Probably I misunderstand some basic concept, as far as I am a bit of newbee to web programming.
I have also saved files via chrome.pageCapture.saveAsMHTML with the use of FileReader and in that case MD5 are equal.
What is wrong and is there a way to get equal MD5 for filename and final file while saving .png from Chrome extension?
I'm attempting to consume server-side code that is owned by another team and that I can't easily change. It is processing an image and returning it via Response.BinaryWrite:
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
var imageToReturn = ms.ToArray();
Response.ContentType = "image/jpg";
Response.BinaryWrite(imageToReturn);
However, when I attempt to do standard client-side processing of the result, like using Javascript's btoa() to convert it from a byte array to an ArrayBuffer, I get messages like "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range".
I really just want to be able to display and work with this image - so any approach that would get it to appear in a canvas, or convert it to a data URL, etc., would help me out. Am I missing something?
If you just want to display the image, why don't you just src attribute of img tag to the url of the ASP.Net page, which is writing the JPG in the in the response.
If you want to display the image in canvas, you can do it in following way
myimage = new Image();
myimage.onload = function () {
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
ctx.drawImage(myimage, x, y);
}
myimage.src = '<url to the asp.net page>';
I am working on a FineUploader implementation. Special request is to create thumbnails on the fly client-side and then upload those with the original image-upload.
I have an implementation that works on FF, but does not seem to work on iOs. It looks like so:
var uploader = new qq.FineUploaderBasic({
button: document.getElementById(buttonID),
request: {
endpoint: '/up/load/a/' + $('section#ajax-viewport').data('albumid')
},
callbacks: {
onSubmit: function(id, fileName) {
// getFile obtains the file being uploaded
file = this.getFile(id);
// create a thumbnail & upload it:
ThumbDown(file, id, 200, fileName);
},
}
})
This code calls a function:
function ThumbDown(file, id, dimension, fileName) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement("img");
img.onload = function (ev) {
var thumbnailDimensions; // object holding width & height of thumbnail
var c=document.getElementById("canvas-for-thumbnails"); // must be a <canvas> element
var ctx=c.getContext("2d");
// set thumbnail dimensions of canvas:
thumbnailDimensions = calcThumbnailDimension (img.width, img.height, dimension )
c.width = thumbnailDimensions.width;
c.height = thumbnailDimensions.height;
var ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0, c.width, c.height);
uploadThumbnail(c.toDataURL('image/jpeg'), //a base64 encoded representation of the image
id,
fileName); // we need filename to combine with mother-image on the server
};
img.src = e.target.result;
}
reader.readAsDataURL(file);
} // end function
Finally the Thumbnail is uploaded with a dumb ajax-call:
function uploadThumbnail (base64encodedString, id, fileName) {
$.post('/up/thumb',
{
img : base64encodedString,
id: id,
fileName: fileName
},
function(data) {});
}
My questions:
1) Currently I have two uploads: one for mother-image and another for thumbnail. I would like to combine this in one FineUploader call. However, I do not see a way to do this, due to the asynchronous nature of my thumbnail creation.
Am I missing something? Is this possible to reduce this to one FineUploader call?
2) This code uploads the thumbnails as a base64 encoded string. I would like to upload the thumbnail as an image (or as a blob ?). Perhaps by following this recipe of Jeremy Banks. Would that work with FineUploader?
3) Are there other options/methods of FineUploader that I have missed but I should be using?
Any help is, as always, greatly appreciated.
So, it is already trivial to upload the original image. Fine Uploader takes care of that for you. If I understand correctly, you want to also upload a scaled version of the image (which you have already generated). I suggest you take the image you have drawn onto the canvas and convert it to a Blob. Then, you can submit this Blob directly to Fine Uploader, where it will upload it for you.
For example, change the value of uploadThumbnail to this:
function uploadThumbnail(thumbnailDataUri, id, filename) {
var imageBlob = getImageBlob(thumbnailDataUri, "image/jpeg"),
blobData = {
name: filename,
blob: imageBlob
};
// This will instruct Fine Uploader to upload the scaled image
uploader.addBlobs(blobData);
}
function getImageBlob(dataUri, type) {
var binary = atob(dataUri.split(',')[1]),
array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: type});
}
Note: the getImageBlob function was adapted from this Stack Overflow answer. If this works for you, be sure to upvote the answer I've linked to.
Server-side note
A Blob is pretty much a File without a name property. Your server-side code will handle the upload of a Blob pretty much the same way as it does a File or form submit containing a <input type="file"> form field. The only noticeable difference to your server will be the filename parameter value in the Content-Disposition header of the multipart boundary containing the file. To put it another way, your server may think the image is named "blob" or perhaps some other generic name, due to the way most browsers generate multipart encoded requests that contain Blob objects. Fine Uploader should be able to get around that by explicitly specifying a file name for the browser to include in blob's Content-Disposition header, but this ability does not have wide browser support. Fine Uploader gets around this limitation, to some degree, by including a "qqfilename" parameter with the request containing the actual name of the Blob.
Future native support for thumbnail generation & scaling
The plan is to add native support for thumbnail previews to Fine Uploader. This is covered in feature requests #868 and #896. There are other related feature requests open, such as image rotation and validation related to images. These features and other image-related features will likely be added to Fine Uploader in the very near future. Be sure to comment on the existing feature requests or add additional requests if you'd like.
As of version 4.4 of FineUploader, as Ray Nicholus pointed out would eventually happen, this functionality has been baked into their framework.
Here is an example of setting the upload sizes when creating a FineUploader instance:
var uploader = new qq.FineUploader({
...
scaling: {
sizes: [
{name: "small", maxSize: 100},
{name: "medium", maxSize: 300}
]
}
});
See their page on uploading scaled images.
Here's my sample code:
var input = document.createElement('input');
input.type = 'file';
document.body.appendChild(input);
input.addEventListener('change', function(){
var file = input.files[0];
var reader = new FileReader();
reader.onload = function(e){
var image = new Image();
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
Load the page, select a large image (I'm using a 2.9MB 4288x3216 image). Refresh the page and select the same image. Result? The tab crashes! (Aw, Snap!)
My guess is that this is a bug with Chrome's implementation of the File API, but I'd love it if someone could confirm that and maybe even offer a workaround. I really want to be able to show a thumbnail of a photo without having to go to the server to generate one (even if it's just for Chrome and FF).
Also, with my sample code above, as soon as you select the photo, the tab starts using about 32MB more of memory. That, I guess, is expected, but what concerns me is that the memory never seems to get freed by the garbage collector. So if I keep selecting more photos, I keep consuming more memory. I don't know if this is related to the crashing issue or not, but it's definitely a concern.
Thanks for any help!
The memory issue could be a result of this bug: http://crbug.com/36142. Essentially, Chrome is caches data: URLs and currently does not release the memory when the img.src is changed. The other issue is that data: URLs yield a 33% overhead to the data you're encoding. That means you're actually setting a ~3.85MB resource on the image, not 2.9MB.
Since you're not manipulating the content (the actual bytes), there's no need to read the file content. One option is to create a blob: url. There's also an explicit revoke method, so you won't run into the same memory caching issues. Something like:
input.addEventListener('change', function(e) {
var file = input.files[0];
window.URL = window.webkitURL || window.URL; // Vendor prefixed in Chrome.
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(file);
document.body.appendChild(img);
});