Retrieve e.target.files in another method in Vue2 - vuejs2

I'm new to Vue.
How can I access e.target.files from submit()?
Tried refs - this.$refs.myFileInput.value but it not gives me FileList{File(17050)...} object.
console.log(e.target.files[0]) in imageChanged(e) gives what I need: File(17050) {name: "hello.jpg", size: 17050, ...}
Now the code:
imageChanged (e) {
console.log(e.target.files[0])
let files = e.target.files
for (var i = files.length - 1; i >= 0; i--) {
let fileReader = new FileReader()
fileReader.readAsDataURL(files[i])
fileReader.onload = (e) => {
this.attachedFile.allData.push({file: e.target.result, size: files[i].size, type: files[i].type, inputnameispreview: this.picked, webtemplateid: this.$route.params.id, filename: files[i].name})
}
}
},
submit () {
let self = this
api.post('http:..', this.attachedFile)...

Hope you have set ref like this
<input type="file" id="file" ref="myInputFile" class="">
In Js you can access file like this
this.$refs.myInputFile.files
Instead of
this.$refs.myInputFile.value

Related

Virtual Image Path not visible in partial View

bit of a weird one here. I tried finding an answer, but was unable to. New to node.
Problem: My virtual image paths work in my views, but not in my partial view, being the navbar. This navbar has a searchbar, and it is fetching the succulent plants in the db, with the following code:
let searchBar = document.getElementById("searchBar");
searchBar.addEventListener("keyup", searchDatabase);
function searchDatabase() {
const searchResults = document.getElementById("searchResults");
//Reg expressions prevent special characters and only spaces fetching from db
let match = searchBar.value.match(/^[a-zA-Z ]*/);
let match2 = searchBar.value.match(/\s*/);
if (match2[0] === searchBar.value) {
searchResults.innerHTML = "";
return;
}
if (match[0] === searchBar.value) {
fetch("searchSucculents", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ payload: searchBar.value }),
})
.then((res) => res.json())
.then((data) => {
let payload = data.payload;
searchResults.innerHTML = "";
if (payload.length < 1) {
searchResults.innerHTML = "<p>No search results found</p>";
return;
} else if (searchBar.value === "") {
searchResults.innerHTML = "";
return;
} else {
payload.forEach((item, index) => {
if (index > 0) {
searchResults.innerHTML += "<hr>";
}
searchResults.innerHTML +=
`<div class="card" style="width: 18rem;">
<img src="${item.SucculentImagePath}" class="card-img-top" alt="${item.SucculentName}">
<div class="card-body">
<p class="card-text">${item.SucculentName}</p>
</div>
</div>`;
});
}
return;
});
}
searchResults.innerHTML = "";
}
Here is the route:
app.post("/searchSucculents", async (req, res) => {
let payload = req.body.payload.trim();
let search = await Succulent.find({SucculentName: {$regex: new RegExp("^"+payload+".*","i")}}).exec();
//Limit Search Results to 10
search = search.slice(0, 10);
res.send({payload: search});
})
Here's the part in my schema defining the image path:
succulentSchema.virtual('SucculentImagePath').get(function() {
if (this.SucculentImage != null && this.SucculentImageType != null) {
return `data:${this.SucculentImageType};charset=utf-8;base64,${this.SucculentImage.toString('base64')}`
}
})
I'm able to reference this image path in my full views, as follows:
<img src="<%= succulent.SucculentImagePath %>">
However, when I try to access the SucculentImagePath attribute in this searchbar in my nav, it is undefined. Am I missing something here?
After doing further research, I discovered that you cant use mongoose virtuals when parsing data to JSON (noob mistake, I know).
I fixed it, by adding this as an option in the schema object:
toJSON: { virtuals: true } })

Multiple Pdf Viewer Add Same Page Via Vue Pdf App Component

I want to show two different pdf file (pdf and pdf2) on same page via one component.
When I try to like below, the second pdf file not shown in the page. Do you have any suggestion
<div id="app">
<vue-pdf-app style="height: 50vh;" :pdf="pdf" :config="config"></vue-pdf-app>
<vue-pdf-app style="height: 50vh;" :pdf="pdf2" :config="config"></vue-pdf-app>
</div>
And here is my javascript codes.
new Vue({
components: {
VuePdfApp: window["vue-pdf-app"]
},
data() {
return {
config: {
toolbar: {
toolbarViewerLeft: { findbar: false }
}
},
pdf: getPdf(),
pdf2: getPdf()
};
}
}).$mount("#app");
function getPdf() {
const pdf2 =" base 64 string pdf";
const pdf = "base 64 string pdf1 ";
return base64ToArrayBuffer(pdf);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
Here is my code on codepen
https://codepen.io/canbeywas/pen/yLMpEBg
You can fix this by slightly modifying your code like this:
new Vue({
components: {
VuePdfApp: window["vue-pdf-app"]
},
data() {
return {
config: {
toolbar: {
toolbarViewerLeft: { findbar: false }
}
},
pdf: getPdf(),
pdf2: getPdf2()
};
}
}).$mount("#app");
function getPdf() {
const pdf = "base 64 string pdf1 ";
return base64ToArrayBuffer(pdf);
}
function getPdf2() {
const pdf = "base 64 string pdf2 ";
return base64ToArrayBuffer(pdf);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}

I cannot integrate js query file in vue

i would like to use a js query code that I found on codepen in my vue project, but im not sure How to integrate it .
I simply pasted the file in my created() of my vue component but it doesn seem to work out.. the code is supposing to run a visual animation when typing chinese caractere in the input form.
this is the codepen : https://codepen.io/simeydotme/pen/CFcke
var $input = $('input');
$input.on({
"focus": function(e) {
$(".input-container").addClass("active");
},
"blur": function(e) {
$(".input-container").removeClass("active");
}
});
var previous = null;
setInterval( function() {
if( previous !== $input.val()
|| "" === $input.val()) {
getGoodCharacters( $input );
previous = $input.val();
}
}, 500);
function getGoodCharacters( $this ) {
var output = $this.val().trim();
var letters = output.split("");
var url = "https://service.goodcharacters.com/images/han/$$$.gif";
$(".error-container, .help").removeClass("show");
$(".output-container").empty();
for( letter in letters ) {
var img = letters[letter] + "";
var newurl = url.replace("$$$",img);
loadCharacter( newurl , img );
}
}
function loadCharacter( url , letter ) {
var img = new Image();
var $output = $(".output-container");
var $a = $("<a/>");
var l = $("input").val().length;
var cwidth = "120px";
if( l > 7 ) { cwidth = "70px"; }
else if( l > 6 ) { cwidth = "90px"; }
else if( l > 5 ) { cwidth = "100px"; }
$(img).load(function(){
$a.attr({
"href": url,
"title": "Good Character Chinese Symbol: "+ letter + ""
}).css("width", cwidth ).append( $(this) ).appendTo($output);
$(".help").addClass("show");
}).attr({
src: url
}).error(function(){
$(".error-container").addClass("show");
});
}
var $try = $(".tryme a").on("click", function(e) {
e.preventDefault();
$input.val( $(this).text() );
});
I also imported the jquery module in my componant
import $ from "jquery";
here is the html that i added in the template
<div class="container input-container">
<input type="text" id="input" placeholder="中文" value="中文"/>
</div>
Thanks!

Image not displayed after camera click on some of the android devices

I am using camera in my website, in mobile phone browser I am having some problems, in some of the phone browser after clicking the camera, Image not displayed, Its show a blank image icon.
Can u plz find out what is the problem in my code?
(function () {
var takePicture = document.querySelector("#take-picture"),
showPicture = document.querySelector("#show-picture");
if (takePicture && showPicture) {
// Set events
takePicture.onchange = function (event) {
// Get a reference to the taken picture or chosen file
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
try {
// Get window.URL object
var URL = window.URL || window.webkitURL;
// Create ObjectURL
var imgURL = URL.createObjectURL(file);
// Set img src to ObjectURL
showPicture.src = imgURL;
// Revoke ObjectURL
URL.revokeObjectURL(imgURL);
}
catch (e) {
try {
// Fallback if createObjectURL is not supported
var fileReader = new FileReader();
fileReader.onload = function (event) {
showPicture.src = event.target.result;
};
// fileReader.readAsDataURL(file);
fileReader.readAsBinaryString(file);
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
switch(exif.Orientation){
case 8:
showPicture.rotate(90*Math.PI/180);
break;
case 3:
showPicture.rotate(180*Math.PI/180);
break;
case 6:
showPicture.rotate(-90*Math.PI/180);
break;
}
}
catch (e) {
// Display error message
var error = document.querySelector("#error");
if (error) {
error.innerHTML = "Neither createObjectURL or FileReader are supported";
}
}
}
}
};
}
})();
<input type="file" id="take-picture" accept="image/*">
<div id="mobilecameraOutput"> <img src="about:blank" alt="" id="show-picture" /></div>

How to redirect to file picker

I am a freshman on skydrive. then I want to use file picker in html, and copy the demo code from Interactive Live SDK. but the running result, the open window is not direct to file picker page, just direct to my setting redirect_uri page. so what's wrong with my demo page? thanks
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/JavaScript">
<!--
/////////////////////////////
WL.init({ client_id: '$my appID', redirect_uri: 'http://www.learnyouwant.com' });
WL.ui({
name: "skydrivepicker",
element: "downloadFile_div",
mode: "open",
select: "multi",
onselected: onDownloadFileCompleted,
onerror: onDownloadFileError
});
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'single'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.download({ "path": file.id + "/content" });
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
function onDownloadFileCompleted(response) {
var msg = "";
// For each folder selected...
if (response.data.folders.length > 0) {
for (folder = 0; folder < response.data.folders.length; folder++) {
// Use folder IDs to iterate through child folders and files as needed.
msg += "\n" + response.data.folders[folder].id;
}
}
// For each file selected...
if (response.data.files.length > 0) {
for (file = 0; file < response.data.files.length; file++) {
// Use file IDs to iterate through files as needed.
msg += "\n" + response.data.files[file].id;
}
}
log(msg);
};
function onDownloadFileError(responseFailed) {
log(responseFailed.error.message);
}
//-->
</script>
I found the reason. the redirect_uri must same with the filling in the app registeration.