Raw Binary Data for Microsoft Cognitive Service API - node.js

For the Microsoft Azure Cognitive Services API, the image needs to be passed in this format
Input passed within the POST body. Supported input methods: raw image binary.
So, I was very lost on how to convert the image the user is uploading into that format and make an API request. I'm using ReactJS on the front-end with a NodeJs backend. Could someone please help me get the image in the correct format? I'm not sure whether I have to read it in as an Array Buffer?
import React, { Component } from 'react';
import Button from 'react-bootstrap/Button';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state ={
file: null
}
}
onSubmit = () => {
console.log(this.state.file);
// console.log(window.atob(this.state.file));
}
onChange = (e) => {
const file = e.target.files[0];
const reader = new FileReader()
reader.addEventListener("load", () => {
// convert image file to base64 string
console.log(reader);
// if (reader.result.includes("data:image/png;base64,")) {
// img = reader.result.replace("data:image/png;base64,", "");
// } else {
// img = reader.result.replace("data:image/jpeg;base64,", "");
// }
//this.setState({file: img});
}, false);
if (file) {
reader.readAsArrayBuffer(file);
}
}
render() {
return(
<div>
<h3 style={{padding: '20px', textAlign: 'center', color: 'white', fontWeight: '100'}}>
Customize your playlist based on your mood!
</h3>
<h5 style={{margin: '30px', padding: '0px',textAlign: 'center', color: 'grey', display:'block'}}>
Click a picture of your surroundings or simply upload one based on what you're currently in the mood for and
<br />
<br />
TuneIn will add a playlist according to your liking!
</h5>
<form onSubmit={this.onSubmit}>
<h1>File Upload</h1>
<input type="file" accept="image/png, image/jpeg" onChange={this.onChange}/>
<button type="submit">Upload</button>
</form>
</div>
);
}
}
export default Dashboard;

Here is the sample for Analyzing a local image using the Computer Vision REST API and javascript.
https://github.com/Azure-Samples/cognitive-services-quickstart-code/blob/master/javascript/ComputerVision/ComputerVisionQuickstart.js

Related

Wrapping code inside styled component in React.js yields unexpected results on show password button click

App.js:
import './App.css';
import React, { Component } from 'react'
import Register from './Components/Register';
import Greet from './Components/Greet';
class App extends Component {
constructor(props) {
super(props)
this.state = {
isRegistered: false,
name: null,
email: null,
password: null,
showPass:false,
}
}
registerHandler=(e) => {
e.preventDefault();
const name = e.target.name.value;
const email = e.target.email.value;
const password = e.target.password.value;
this.setState({ isRegistered: true,name,email,password});
}
showPassHandler=()=>{
this.setState({showPass:!(this.state.showPass)});
}
render() {
return (
<div>
{this.state.isRegistered?<Greet name={this.state.name} email={this.state.email}/>:<Register submit={this.registerHandler} click ={this.showPassHandler} showPass={this.state.showPass}/>}
</div>
)
}
}
export default App;
/////////////////////////////////////////////////////////////
Register.js:
import React,{useState} from 'react'
import Styled from "styled-components";
export default function Register(props) {
const btnStyle={
backgroundColor:"red",
color:"white",
}
// const savePassword=(val)=>{
// show=val.target.value;
// val.target.value=show;
// inputRef.current.focus();
// val.target.focus();
// console.log(show);
// setPass(show);
// }
// console.log(show);
let btnText;
const btnClasses = ["btn","m-1","mt-2"];
if(props.showPass===true)
{
btnStyle.backgroundColor = "green";
btnText="hide password";
btnClasses.push("btn-primary");
}
else{
btnText="show password";
btnClasses.push("btn-danger");
}
const StyledButton = Styled.button
`
background-color: ${(props)=>props.bgColor};
color: white;
display:${(props)=>props.flag==="1"?"inline-block":"block"};
width:${(props)=>props.flag==="1"?"45%":"100%"};
margin:5px;
`
const StyledRegisterContainer = Styled.div`
width:600px;
&:hover {box-shadow:0px 0px 5px grey};
#media (min-width:0px) and (max-width:600px) {
width:300px;
};
`;
//register-container=> was class inside most outer div
return (
<StyledRegisterContainer className='container card mt-4 p-3 '>
<h1 className='text-center'>
Registration Form
</h1>
<form onSubmit={props.submit}>
<div className='form-group'>
<label className='control-label' htmlFor='name'>Name:</label>
<input type='text' name='name' className='form-control'/>
</div>
<div className='form-group'>
<label className='control-label' htmlFor='email'>Email:</label>
<input type='email' name='email' className='form-control'/>
</div>
<div className='form-group'>
<label className='control-label' htmlFor='password'>password:</label>
<input type={props.showPass?"text":"password"} name='password' required className='form-control' />
</div>
<button type='submit' className='btn btn-primary mt-2 m-1'>
Register
</button>
<button type ="button" className={btnClasses.join(" ")} onClick={props.click}>
{btnText}
</button>
<br/>
<StyledButton flag="1" bgColor="orange">Login</StyledButton>
<StyledButton flag="1" bgColor="blue">Login</StyledButton>
<StyledButton flag="0" bgColor="brown">Login</StyledButton>
</form>
</StyledRegisterContainer>
)
}
//style = {btnStyle}//it was inside button =>show password
inside Register.js file everything was working perfect but when I wrapped the code inside StyledRegisterContainer(a styled component) the functionality of show password button is disturbed and the moment I click on show password button the text from input box disapears.
I want my code to work even after wrapping it inside the above mentioned styled component.
I am not familiar with styled-components, but according to their documentation, it seems like you're importing Styled instead of styled
import styled from 'styled-components';
https://styled-components.com/docs/basics#installation

React - trying to save fetched data in a variable but the variable returns empty

I fetched json data with async await and i wanted to save the fetched data in a variable in order to be able to use it with a map in my component,
the data comes in properly inside the function - i checked with an alert , and also in the variable inside the function it does display all the data , but somehow the variable outside the function returns empty .
here is some code:
both alerts in the following code return the right data.
export let fetchPosts = [];
export async function FetchPosts() {
await axios.get('https://jsonplaceholder.typicode.com/posts').then(
res => {
alert(JSON.stringify(res.data))
fetchPosts = JSON.stringify(res.data);
alert(fetchPosts)
}
).catch(err => {
alert('err');
})
}
import { fetchPosts } from '../services/post';
import { FetchPosts } from '../services/post';
export default function Posts() {
function clickme() {
FetchPosts()
}
return (<>
<button onClick={clickme}>Click me</button>
{fetchPosts.map((post, index) => (
<div key={post.id} className="card" style={{ 'width': '16rem', 'display': 'inline-block', 'margin': '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
State is the issue
React doesn't automatically reload on your singleton fetchPosts.
Instead, try...
export function FetchPosts() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
then
import { useState } from 'react';
import { FetchPosts } from '../services/post';
export default function Posts() {
const [posts, setPosts] = useState([]);
function clickme() {
FetchPosts().then(res => {
setPosts(res.data);
});
}
return (<>
<button onClick={clickme}>Click me</button>
{posts.map((post, index) => (
<div key={post.id} className="card" style={{ width: '16rem', display: 'inline-block', margin: '5px' }}>
<div className="card-body">
<h6 className="title">{post.title}</h6>
<p className="card-text">{post.body}</p>
</div>
</div>
))}
</>)
}
https://codesandbox.io/s/jolly-almeida-q4331?fontsize=14&hidenavigation=1&theme=dark
If you want global state, that's another topic you should dive into entirely but you can do it with a singleton, you just need to incorporate it with hooks and an event emitter. I have a bit of a hacked version of this here https://codesandbox.io/s/react-typescript-playground-forked-h8rpu but you should probably stick to redux or mobx or AppContext which is more of a popular pattern.

Unable to get Stripe elements to work with Vue.js

I am trying to get it so that a Vue component (currently have as just a route/view), will be able to display a styled version of Stripe Elements form for entering credit cards.
One other issue I am having is that I don't want to have the stripe js file loaded with every page like it does when in index.html. I am instead looking for it to just load on a single component/view.
My end idea is that I will have a button that when clicked will display a bootstrap modal and will show the Stripe Elements form which they then will enter their credit card info into which will, in turn, give me a token which I can then send to my backend along with an auth (JWT) header to do processing on my API.
So far I have tried mounting, creating, vue-strip-elements-plus examples and many more things.
I've included the entire Billing.vue file minus my stripe API key
I am not picky on how I do it whether it be with the way from the stripe docs or the package mentioned above.
<div class="container">
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button v-on:click="update">Submit Payment</button>
</form>
</div>
</template>
<script>
// Create a Stripe client.
var stripe = Stripe('pk_test_<key>');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {
hidePostalCode: true,
style: style
})
export default {
name: 'Billing',
data() {
},
mounted() {
card.mount('#card-element');
},
update: function() {
stripe.createToken(card).then(function(result) {
// Access the token with result.token
console.log(result.token) // I'd then send the token using axios to my backend
});
}
}
</script>```
I am expecting the token to currently be console.log which I can check in my browser

How to upload an image in mongoose-node app using ckeditor. File will be uploaded to s3

I'm using CKEditor to upload content in mongoose.
I want images to be uploaded along with the content.
I'm storing the images to s3 and mongodb stores the image path in string (when not uploading with ckeditor).
I'm trying to use this module
https://github.com/mjadobson/ckeditor5-sss-upload
I'm trying this code
build-config.js
module.exports = {
// ...
plugins: [
"#ckeditor/ckeditor5-essentials/src/essentials",
// ...
//'#ckeditor/ckeditor5-adapter-ckfinder/src/uploadadapter',
//'#ckeditor/ckeditor5-easy-image/src/easyimage',
"ckeditor5-sss-upload/src/s3upload"
// ...
],
// ...
config: {
toolbar: {
items: [
"headings",
"bold",
"italic",
"imageUpload",
"link",
"bulletedList",
"numberedList",
"blockQuote",
"undo",
"redo"
]
}
// ...
}
};
seminar.js
const build_config=require('../build-config');
router.get('/add',ensureAuthenticated,(req,res)=>{
SeminarGamenameConf.find().then(gameName_list=>{
SeminarGametypeConf.find().then(gameType_list=>{
console.log(gameType_list);
res.render('cms/seminar/add',{
gameName_list_array:gameName_list,
gameType_list_array:gameType_list,
country: countries,
build_config:build_config
});
})
})
});
//add.handlebars
<script src="/ckeditor5-build-classic/ckeditor.js"></script>
<form action="/cms/seminar/add" enctype="multipart/form-data" method="post" >
<div class="form-group">
<label for="seminar_detail">Seminar Details</label>
<textarea class="form-control" id="editor1" name="seminar_detail</textarea>
<input type="submit" value="submit"/>
</div>
</form>
<script>
ClassicEditor.create(document.querySelector("#editor"), {
s3Upload: {
policyUrl: "http://127.0.0.1/my-upload-endpoint",
mapUrl: ({ location, bucket, key }) => {
return location;
}
}
});
</script>
I'm really confused. I don't know how to upload images to s3 using ckeditor (in between the details).
Please help.
If there is any other method, please reply

Can't Edit and Update properties with form Reactjs and MongoDB

So I'm using Nodejs, MongoDB and Reactjs
and I'm trying to Edit properties of projects.
I have multiple projects and when I want to edit properties of one I can't do it. We can access to properties inside inputs, we can see Title and Type but can't even delete, write, he access to properties by its ID but then I can't change it, I guess I have multiple problems here than.
I'll write here my server code, and my Edit/Update project page and a gif with an example when I say that I can't even change anything on inputs.
My server code:
//Render Edit Project Page byId
app.get('/dashboard/project/:id/edit', function(req, res){
let id = req.params.id;
Project.findById(id).exec((err, project) => {
if (err) {
console.log(err);
}
res.json(project);
});
}
//Update Projects Properties byId
app.put('/dashboard/project/:id/edit', function(req, res){
var id = req.params.id;
var project = {
title: req.body.title,
typeOfProduction: req.body.typeOfProduction
};
Project.findByIdAndUpdate(id, project, {new: true},
function(err){
if(err){
console.log(err);
}
res.json(project);
})
};
My React Component Edit Project Page
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './EditProject.css';
class EditProject extends Component {
constructor(props){
super(props);
this.state = {
//project: {}
title: '',
typeOfProduction: ''
};
}
inputChangedHandler = (event) => {
const updatedProject = event.target.value;
}
componentDidMount() {
// console.log("PROPS " + JSON.stringify(this.props));
const { match: { params } } = this.props;
fetch(`/dashboard/project/${params.id}/edit`)
.then(response => { return response.json()
}).then(project => {
console.log(JSON.stringify(project));
this.setState({
//project: project
title: project.title,
typeOfProduction: project.typeOfProduction
})
})
}
render() {
return (
<div className="EditProject"> EDIT
<form method="POST" action="/dashboard/project/${params.id}/edit?_method=PUT">
<div className="form-group container">
<label className="form--title">Title</label>
<input type="text" className="form-control " value={this.state.title} name="title" ref="title" onChange={(event)=>this.inputChangedHandler(event)}/>
</div>
<div className="form-group container">
<label className="form--title">Type of Production</label>
<input type="text" className="form-control " value={this.state.typeOfProduction} name="typeOfProduction" ref="typeOfProduction" onChange={(event)=>this.inputChangedHandler(event)}/>
</div>
<div className="form-group container button">
<button type="submit" className="btn btn-default" value="Submit" onClcik={() => onsubmit(form)}>Update</button>
</div>
</form>
</div>
);
}
}
export default EditProject;
Erros that I have:
1- DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.
2- Inputs can't change
3- When click "Update" button:
I think your update override the entire object because you forgot the $set operator. This is the operator to change only the atributtes of an object and not the entire object replacing!
Example:
Model.update(query, { $set: { name: 'jason bourne' }}, options, callback)
First of all, concerning the deprecation warning, you need to change the method findAndModify (As I do not see it here, I guess you're using it elsewhere, or maybe one of the methods you use is calling it) by one of the suggested methods and change your code accordingly.
Then, you need to learn about React and controlled components : https://reactjs.org/docs/forms.html
You need to set the component's state in your onChange handler, such as :
this.setState({
title: event.target.value // or typeOfProduction, depending on wich element fired the event
});
This is called a controlled component in React.
Concerning the response body you get when clicking on Update button, this is actually what you asked for :
res.json(project);
returns the project variable as a JSON file, which is displayed on your screenshot.
See this question for more information about it : Proper way to return JSON using node or Express
Try replace "value" in input tag with "placeholder"

Resources