Copy & Paste Filepicker Upload / How to manually upload data to Filepicker? - javascript

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 :)

Related

Upload and view an input file using VueJS

I am using TypeScript and Haml. I want to be able to upload and view a file using vue.js. I am able to upload an image but it is supposed to display it right away as demoed here: https://codepen.io/Atinux/pen/qOvawK/
Instead, I get this error:
http://localhost:8080/image Failed to load resource: the server responded with a status of 404 (Not Found)
If it's trying to get the image from the root directory, is my issue that I'm not saving it there? How would I solve this?
page_image.ts:
require("./page_image.scss");
import Vue = require("vue");
import {Injections} from "../../init";
export const PageImage = {
template: require("./page_image.haml"),
data: function () {
return {
image: ''
}
},
created() {
Injections.HeaderTextManager.setHeader("Videos");
Injections.HeaderTextManager.clearDescription();
},
methods: {
onFileChange(e:any) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file:any) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e:any) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e:any) {
this.image = '';
}
}
};
page_image.haml:
.page-image
.row
.col-xs-12
.box
.box-header
%div(v-if="!image")
%h3.box-title Upload an image
%input(type="file" v-on:change="onFileChange")
%div(v-else)
%img(src="image" name="image")
%img {{image}}
%button(v-on:click="removeImage") Remove image
I don't know haml, and I do not use typescript with vue.js. So I cannot give you a direct answer.
Here is a working jsFiddle example that implements FileReader with vue.js to provide an instant preview:
https://jsfiddle.net/mani04/5zyozvx8/
You may use the above for reference to debug your code.
Here is how it works: To make FileReader work properly, we need access to the DOM element for input. This can be accomplished as shown below:
<input type="file" #change="previewImage" accept="image/*">
The previewImage method gets the event parameter, which has event.target - the DOM element for input that we need. Now your previewImage method can read the image file normally as follows:
previewImage: function(event) {
// Reference to the DOM input element
var input = event.target;
// Ensure that you have a file before attempting to read it
if (input.files && input.files[0]) {
// create a new FileReader to read this image and convert to base64 format
var reader = new FileReader();
// and so on...
You may use this jsFiddle for reference, and keep this question open, so that others with knowledge of haml and typescript may provide a more direct answer.
I think the problem is caused because of this line in your page_image.haml
%img(src="image" name="image")
If it translates or compiles to <image src="image" name="image">, then your browser will look for image in localhost:8080/image instead of attempting to show from data.image inside Vue component.
As explained in my other answer, I dont know haml, so you have to figure out a way to fix it yourself.
Edit:
Looking at the other haml code in your question, does this work?
%img(v-bind:src="image" name="image")

error css class not applied in custom file input tag and jquery validation counting was not happening where unsupported format image upload

First of all Sorry for the length heading. Currently working on custom file input where with my current code i can able to upload the only jpeg file if the user uploading some other format it will show error message you have to upload only jpg
when the user click the next button jquery should validate the file input and it should say in the message you have missed one field currently I gave required for the input field still it was not validting the field. I am struggling lot not getting anything in my mind help me.
Here is the jquery code
function showImage() {
var files = !! this.files ? this.files : [];
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg)$/;
// No file selected, or no FileReader support
if (!files.length || !window.FileReader) return;
// If the file is a JPEG image
if (regex.test(files[0].type)) {
// Create an instance of FileReader
var reader = new FileReader();
// Declare the onload callback before reading the file
reader.onload = function () {
// Set image data as background of div
$preview.css("background-image", "url(" + this.result + ")");
// Empty the error message
$errorLabel.text('');
// Disable file selection
$fileInput.prop('disabled', true);
// Show the buttons
$deleteBtn.show();
$sendBtn.show();
$imagecontainer.hide();
};
// Read the local file
reader.readAsDataURL(files[0]);
} else {
// Add an error message
$errorLabel.text('Please upload only jpeg');
$errorLabel.css("color","red");
$fileInput.addClass('errRed');
}
}
Here is the fiddle link
Kindly please guide me
Thanks in advance
html code
<input name="Select File upload" accept="image/jpeg" required class="upload" id="upload" type="file" />
Now I gave new property call accept input file user can upload only jpeg image this was happening correctly but my validation count was not reduced with this :(
Your regex won't validate against the type attribute, as it returns the MIME type of the file, and your regex is looking at the file extension. Use the name attribute instead if you want to keep using that regex.
In other words, try changing
regex.test(files[0].type)
to
regex.test(files[0].name)
Finally after long hours i found the answer for this issue :) I need to put one single line that was the most funniest part here.
this is the line which was so much time i need to put this line in the condition :) $(".basicForm").validate().element("#upload");
if (regex.test(files[0].type)) {
// Create an instance of FileReader
var reader = new FileReader();
// Declare the onload callback before reading the file
reader.onload = function () {
// Set image data as background of div
$preview.css("background-image", "url(" + this.result + ")");
// Empty the error message
$errorLabel.text('');
//$('.choose_file').removeClass('errRed');
$(".basicForm").validate().element("#upload");
$('#imageUploadForm').removeClass('errRed');
// validate();
// Disable file selection
$fileInput.prop('disabled', true);
// Show the buttons
$deleteBtn.show();
$sendBtn.show();
$imagecontainer.hide();
};
// Read the local file
reader.readAsDataURL(files[0]);
} else {
//alert("sorry not an jpeg file");
// Add an error message
$(".basicForm").validate().element(".upload");
$fileInput.val('');
$errorLabel.text('Please upload only jpeg');
$errorLabel.css("color","red");
$fileInput.addClass('errRed');
//$(event).preventDefault();
var control = $("#files");
control.replaceWith( control = control.clone( true ) );
$(".btn-next").trigger('click');
}

How do i remove files from a zip file uploaded through kendoUpload? Using jszip

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'.

Grabbing local files from drag and drop event and displaying them

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);
}

How do I provide my script with the file system so I can save data to disk?

I have this webpage for converting text to chordpro. Today the content is modified in the text area; forcing me to open a text editor and then paste the text area content there, but I'd rather open a save file dialogue so that the contents can be saved to disk directly. I've tried to figure out how to make use of HTML5 Filesaver and I think I'm almost there, but I can't figure out how to provide the file system (fs)? Chrome keeps telling me fs is undefined (which it is as I haven't provided it).
Am I approaching this the right way and is there anything more than the file system that I need to provide for this to work?
This is how far I've gotten. HTML input is:
<button type="button" onclick=saveTextArea();>Convert</button>
and the Javascript is:
function saveTextArea(fs) {
"use strict";
convertToChordpro(); // Converts text area value to chordpro format
var textArea = document.getElementById('textArea');
var artist = document.getElementById('artist').value;
var title = document.getElementById('title').value;
var fileName = (artist && title) ? artist + "-" + title + ".txt" : "artist-title.txt";
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwrite = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
var bb = new BlobBuilder();
bb.append(textArea.value);
fileWriter.write(bb.getBlob('text/plain'));
}, onError);
}, onError);
}
function onError() {}
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(TEMPORARY, 1024*1024, saveTextArea, onError);
Do something like this
var fs = window.requestFileSystem(TEM...);
saveTextArea(fs);
-- edit --
Define the error handler:
function onError(e) { console.log(e); }
Either the initialization or the error handler must be called. In your case, the error handler will be called (because the initialization handler is not).
But...
The w3c FileSystem API does not provide a file chooser, if that is what you want. Storage is local and cannot be accessed from outside the browser sandbox. The FileSystem API is pretty experimental and currently only supported by Chrome.
Maybe what you want is a simple file upload via <input type="file"> and posting the data to your server?

Categories

Resources