Upload and view an input file using VueJS - javascript

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

Related

How to get full path to user's type="file" using jQuery Fileupload

Im trying to build file preview feature before file being uploaded to the server.
Im stucked with the problem of reading file from the user's computer, not a server
Im usuing jquery Fileupload which fires the file processing on the change function
return $('#new_order_file').fileupload({
change: function(e, data) {
return $.each(data.files, function(index, file) {
read_file(file);
console.log(file)
});
},
});
Log gives File - name, size, type, proto and LastmodifiedDate
Than, this part is tricky for me, I know that I have to use FileReader() but Im not sure how to
function read_file(f){
var reader = new FileReader();
reader.onload = function(e) {
$('#CO-show-model').css('display', 'block');
loaded(f.name, e.target.result);
};
reader.readAsArrayBuffer(f);
}
Next, loaded function is for displaying the file model using three.js
function loaded(file) {
var uploaded_file = file // gives 404
// var uploaded_file = './stl/test-file.stl' // ASCII test
}
The fucntion itself is good, I tested it with an hardcoded path to some test file. But the problem is that it was on a server. Now, script gives an 404 for http://example.com/filename.stl which is true, because I pass file.name there. If I just pass file, it gives 404 for http://example.com/[object%20File]
Edit 1:
I tried suggest ReadAsDataUrl, but seems to be that it's not supported by three.js. Also, the FileReader() seems to be ok
Your file is an object so you have to get the right attribute from it.
Take a look here Filereader Mozilla documentation
It's a security feature. Browsers will not give you the actual local url to the file you are uploading.
See How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
Edit: Maybe what you are looking for is this question instead? What is the preferred method for loading STL files in Three.js

AngularJS read JSON from user upload

I would like to allow user upload a JSON file and assign the content of the JSON file to a $scope variable.
After the content of the file is been assigned to the scope variable, I want to totally discard the file itself and not storing it anywhere.
How to efficiently implement this function?
In your template:
<input type="file" onchange="angular.element(this).scope().onFileChange(this)">
In your JS:
$scope.onFileChange = function (fileEl) {
var files = fileEl.files;
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState === FileReader.DONE) {
$scope.$apply(function () {
$scope.something = JSON.parse(evt.target.result);
});
}
};
reader.readAsText(file);
};
"onchange" instead of "ng-change", because it looks like Angular doesn't support binding things with ng-change on file upload input controls.
This was stolen almost verbatim from a co-worker's code. It might be Chrome-specific. If someone who knows me sees this, all credit is due to this coworker. And it's all due to him in any event anyhow. ;)

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

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

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

input type file not properly putting image into image tag

I was working on something and the question was answered, but i need a different use for it.
I have a jsFiddle of how it works. http://jsfiddle.net/TbZzH/4/
that is fine and dandy, but when i do it in my code, it will tell me that data.files[0] does not work, and is said to be undefined. It also does not recognize the FileReader() object.
My code is as follows, using jsFiddle as an example I worked from.
$(function(){
$("input[type='file'].attribute").on("change", function () { updateDesigner(this); });
});
function updateDesigner(input){
var t = input;
if ($(input).attr("type") == 'file'){
try{
var data = $(t)[0];
var file = data.files[0]; //<------ FAILS HERE. .files is an undefined attr.
var reader = new FileReader(); //<--- working around it, doesnt understand this object as well
reader.onload = function (e) {
value = e.target.result;
}
reader.readAsDataURL(file);
}catch(errrrr){
alert("error putting image into image tag: "+errrrr.toString());
}
}
srcFunction(value); //takes the value and applied it to the src attr of the image tag.
}
I want to pipe the data into value and everything would run smooth, but i am not sure what is going on.
While IE works with some examples, The issues here seem to be related to the websites "trust" and "secureness"
to get a static image to appear on the computer screen, i need to make it a trusted site as well as having the rerouted to https

Categories

Resources