I'm attempting to grab dragged and dropped files from the drop event and displaying the images in an area just so the user knows that the drop was successful. However, I'm unsure how to grab those dropped files and display them in an area. I've attempted to that like so:
$(e.originalEvent.dataTransfer.files).each(function(){
$("#feedBackAreaTest").append("<img src='"+this.name+"' />");
});
However, it only grabbed the name, obviously. My question is, what is the right way of displaying the images dropped? this.name is only grabbing the name and not the link to the file.
File objects are like oysters: you can inspect them superficially, but you can't know what they really have in them until you pry them open and look inside. To do that, you need to use a FileReader to extract the data from each File object:
$(e.originalEvent.dataTransfer.files).each(function(){
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function(readEvent) {
$("#feedBackAreaTest").append("<img src='"+readEvent.target.result+"' />");
}
});
FileReader objects have a few read methods that each take a Blob or File object as an argument (readAsText, readAsDataURL, etc.). When the read operation is done, the FileReaader fires a load event which has the data from the file just read.
Using the FileReader API; I pulled this sample from MDN that you can use:
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function (oFREvent) {
$("#feedBackAreaTest").append("<img src='"+oFREvent.target.result+"' />");
};
function loadImageFile() {
if (document.getElementById("uploadImage").files.length === 0) {
return;
}
var oFile = document.getElementById("uploadImage").files[0];
if (!rFilter.test(oFile.type)) {
alert("You must select a valid image file!");
return;
}
oFReader.readAsDataURL(oFile);
}
Related
I have input file (Multiple) use to upload images. When an image is uploaded it will display as a thumbnail and also as a full view. I already have URL.createObjectURL() that renders the image into blob but when the number of images is more then it is effecting the page a little since each image is having 2 blob-data for thumbnail and full view.
For single file upload it was easy to have URL.createObjectURL() for thumbnails and $(this).val() to generate fake path for full view. But I do not know how to do that with multi file upload.
Sample code:
$('#imageBtn').on('change', function(){
var inputFiles = this.files;
$(inputFiles).each(function(index) {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onloadend = function(){
RenderedPath = URL.createObjectURL(inputFile);
FakePath = inputFile.val();
// Some codes to populate the thumbnail and fullview
}
});
});
So, how can I obtain the fake path for each uploaded image?
I don't see what you want to do with this fakePath. Being a "fake" path, it's of no use.
Historically, (before the File API), it was a way to retrieve the name of a selected File, but now that we've got the File API, this information is provided inside the File object directly.
So if you really want to build it yourself, like in the case of an input[type=file][multiple], then you can simply prepend "C:\fakePath\" to the File's name.
But once again, you won't be able to do anything from this string.
Also note that in your code you don't do anything with the FileReader's result, and anyway, you don't need it at this point, so remove it here, since it is probably one of the causes of your memory issues.
Indeed, BlobURIs in the case of user-provided Files won't use any memory, being simple pointers to the file stored on user-disk, while reading it as a dataURI will actually load the whole data three times in memory.
So for the part you shown, it can simply be
$('input[type="file"]').on('change', function() {
var files = this.files;
$(files).each(function(index, file) {
// Still don't know why you want this...
var fakepath = 'C:\\fakepath\\';
$('body').append('<div>' +
// build a fake path string for each File
'<p class="path">'+ fakepath + file.name + '</p>' +
// all that is really needed to display the image
'<img src="'+URL.createObjectURL(file)+'">' +
'</div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple>
Now, you stated in a comment that you need the FileReader to pass it to jsZip library, if you are talking about this one, then you've to know that it accepts Blobs. So you still don't need a FileReader.
var fileList = [];
$('input[type="file"]').on('change', function() {
var files = this.files;
$(files).each(function(index, file) {
$('body').append($('<img>', {
src: URL.createObjectURL(file),
onload: function() { fileList.push(file); $('button').attr('disabled', false);},
onerror: function() { $(this).remove(); }
}));
});
});
$('button').on('click', function() {
var zip = new JSZip();
fileList.forEach(function(file) {
zip.file(file.name, file);
});
zip.generateAsync({
type: "blob"
})
.then(function(blob) {
saveAs(blob, "myfiles.zip");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<input type="file" multiple accept="image/*">
<button disabled>save as zip</button>
I'm trying to upload an image that the user gives me via copy and paste and I am wondering how to upload such data to Filepicker/Filestack.
My code so far:
var pasteHandler = function (event) {
// turned out to be needed because of jquery
if (event.originalEvent !== undefined) {
event = event.originalEvent;
}
var clipboardData = event.clipboardData;
var items = clipboardData ? clipboardData.items : [];
_.each(items, function (clipboardItem) {
if (clipboardItem.kind == 'file' && clipboardItem.type.indexOf('image/') !== -1) {
var blob = clipboardItem.getAsFile();
var reader = new FileReader();
reader.onload = function (event) {
var fileUrl = event.target.result;
/* I get a fileUrl here that I can assign to an img element and see the result */
filepicker.store(
/*what should I send here?*/,
function(Blob){
console.log(JSON.stringify(Blob));
}
);
};
reader.readAsDataURL(blob)
}
});
};
Can somebody tell me what to send to filepicker/filestack there?
Everything I tried so far resulted in this error:
"Uncaught FilepickerException: Cannot store given input: [object DataTransferItem]. Not a string, file input, DOM File, or FPFile object."
Apparently I can't use an input field with the type "file" as there is no way to set the value of the input field to be the pasted file.
What is a DOM File here? I tried using new File(['testData'], 'test.txt') without success. I get the following error:
"FPError 122: The Remote URL could not be reached. For help, see https://developers.filepicker.io/answers/jsErrors/122"
Which makes me think maybe filepicker.store() is not the right choice for this task as it seems to be expecting an url which I don't have yet (I mean that's what I'm trying to do, right? Getting an url for the uploaded file FROM filepicker).
In the Filepicker API itself I only find examples that use another filepicker method before and therefore already have a valid url for the file.
Thanks in advance,
Jesse :)
I want to make a multiple images upload system with prograss bar. I want to do with simaple code(using jquery or js). I want when user has upload his images on browser and i want to show on browser that images and with upload button he starts uploading image via ajax in his folder.
So questions
1.) Is it possible to show uploaded image (without any complicated code) ?
2.) Do i get a variable or array where uploaded images are stored as base64 code (data:/img:dfd5d/d54fs..... something like this) or encoded?
3.) How do i add progressBar ?
I didn't write any code yet because i dont know how to start. I am new in computer science.
But i find this code on this site
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
This is easy code and i understand but one thing is not clear what does mean this line var reader = new FileReader(); why use new and what is it ?
Ty in advance and please dont explain complicate and i am not very good in english. So please try to explain in poor words if possible..
Assuming that you have this field
<input type="file" onchange="showImage(this)"/>
you can create a script to take the binary data and show it
function showImage(input){
var reader = new FileReader();
// validating...
var fileType = input.files[0].type;
var filesize = input.files[0].size;
// filetype (this will validate mimetype, only png, jpeg, jpg allowed)
var fileTypes = ["image/png", "image/jpeg", "image/gif"];
if (fileTypes.indexOf(fileType) < 0){
// return error, invalid mimetype
return false;
}
// file cannot be more than 500kb
if (filesize > 5000000) {
// return error, image too big
return false;
}
reader.onload = function (e) {
// e will contain the image info
jQuery('#myimagetopreview').attr('src', e.target.result)
}
reader.readAsDataURL(input.files[0]);
}
This should work, if you have problem tell me
edit: FileReader is not supported by all the browsers, check the documentation for more https://developer.mozilla.org/en/docs/Web/API/FileReader
The FileReader in JS has Status "Working Draft" and isn't part of the official JS API. I think you have to wait until the Browsers support this ne API or you have to activate experimental JS API in the Browser.
After the user uploads a zipped file, i want to remove the images folder from it before sending it over the network. I am using kendo for uploading, and the existing functionality works fine. I just want to add on the removing images part. This is what i have so far:
function onSelect(e) {
var file = e.files[0];
if (endsWith(file.name, '.eds')) {
var contents = e.target.result;
var jszip = new JSZip(contents);
jszip.remove("apldbio/sds/images_barcode");
fileToSend = jszip.generate({type: "base64", compression: "DEFLATE"});
}
e.files[0] = fileToSend;
openProgressDialog(e.files.length); //this is existing code, works fine
}
target.result doesn't seem to exist in the event e. And nothing works properly from that point on. e should probably be used inside a FileReader object's onload(), (as seen here and here) but i have no idea how to use a FileReader for my purpose, with kendo Upload.
EDIT:I did some more reading and now i am using FileReader like this:
var reader = new FileReader();
reader.onload = function (e) {
// do the jszip stuff here with e.target.result
};
reader.onerror = function (e) {
console.error(e);
};
reader.readAsArrayBuffer(file);
Note : file = e.files[0] as in the 1st code block.
With this though, i get the error:
Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
I get the original code from here: Using Javascript FileReader with huge files
But my purpose is different, the author wants to get just a part of the whole but I want them all.
I'm trying modify it with loop, mixed with this technique: slice large file into chunks and upload using ajax and html5 FileReader
All fails, is there anyway I can get what I want.
var getSource = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
if (e.target.readyState == FileReader.DONE) {
process(e.target.result);
}
};
var part = file.slice(0, 1024*1024);
reader.readAsBinaryString(part);
};
function process(data) {
// data processes here
}
Thank you,