I am writing a page where the user should put some information in two text areas, and this text data should write into DB. The row in DB creates with NULL in these two areas and DateTime is written there.
So in my database I have id|usuario_nombre|file_nombre|created_at| updated_at
and usuario_nombre|file_nombre have NULL, and others have information.
Can you help, please?
Controller :
'use strict'
const Upload = use('App/Models/Upload')
class UploadController {
async index({ view })
{
const uploads = await Upload.all();
return view.render('/', {
uploads: uploads.toJSON()
})
}
async create({ view })
{
return view.render('/upload');
}
async store({ request, response })
{
const upload = new Upload();
upload.usuario_nombre = request.input('usuario_nombre');
upload.file_nombre = request.input('profilefile');
upload.save();
response.redirect('/');
}
}
module.exports = UploadController
Form with inputs :
<form method="POST" enctype="multipart/form-data">
{{ csrfField() }}
<input type="text" id="usuario_nombre" name="usuario_nombre"/>
<input type="text" name="profilefile" id="profilefile"/>
<button type="submit"> Submit </button>
</form>
Routes :
Route.get('/upload/create', 'UploadController.create')
Route.get('/upload', 'UploadController.store')
Route.get('/upload/create', 'UploadController.create')
Route.get('/upload', 'UploadController.store')
Migration :
'use strict'
/** #type {import('#adonisjs/lucid/src/Schema')} */
const Schema = use('Schema')
class UploadsSchema extends Schema {
up() {
this.create('uploads', (table) => {
table.increments()
table.string('usuario_nombre')
table.string('file_nombre')
table.timestamps()
})
}
down() {
this.drop('uploads')
}
}
module.exports = UploadsSchema
Use await upload.save(); because save() is a async operation
Related
I'm fairly new to web development and vue.js.
I have an app where I enter an Id in and on button(search) click it is calling a method. This method makes an axios call to the controller and retrieves data as an object.
This data is displayed in tag (not sure if this approach is correct).
After this data is displayed, when the second time I enter another Id in the field and hit the button, it still displays the old text till it fetches the new data. Once new data is retrieved, it displays the new one.
I want to clear this data everytime I hit the button for search as well as call the vue function to fetch data.
I have tried clearing the data at the beginning of the vue function call but that didn't work.
<input type="text" placeholder="Enter the ID" v-model="mId" />
<button type="button" class="searchgray" v-on:click="SubmitId">Search</button>
<h4 style="display: inline">ID: {{queryData.Id}}</h4>
<strong>Device Status: </strong><span>{{queryData.deviceStatus}}</span>
<script>
export default {
components: {
'slider': Slider,
Slide
},
props:['showMod'],
data() {
return {
mId '',
queryData: {},
}
},
methods: {
SubmitId: function () {
this.queryData = {}
axios.get('/Home/SearchId?Id=' + this.mId)
.then(response => response.data).then(data => {
this.queryData = data
}).catch(err => {
this.queryData = {}
this.mId = ''
alert(`No records found anywhere for the given mId`)
});
}
}
</script>
So in the above code, when I hit the Search button, it calls the SubmitId function and returns queryData. Now when I enter a new mId in input field and hit serach button it continues to display the querydata associated with the old mId till the fetching of data is completed and new query data for the new mId is returned.
I was looking for a way to clear the screen text everytime I hit the button. So I also tried doing queryData={} before the axios call, but it didn't help.
Help appreciated.
new Vue({
el: '#app',
props: [
'showMod'
],
data() {
return {
mId: '',
queryData: {}
}
},
methods: {
async SubmitId () {
const axiosRequest = () => new Promise((resolve, reject) => {
const obj = {
Id: Math.random(),
deviceStatus: Math.random()
}
setTimeout(() => {
resolve(obj)
// reject('Not Found')
}, 2000)
})
try {
this.queryData = {}
this.queryData = await axiosRequest()
} catch (err) {
this.mId = ''
alert('No records found anywhere for the given mId')
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input
v-model="mId"
type="text"
placeholder="Enter the ID"
/>
<button
v-on:click="SubmitId"
type="button"
class="searchgray"
>
Search
</button>
</br>
<h4 style="display: inline">
ID: {{ queryData.Id }}
</h4>
</br>
<strong>Device Status: </strong>
<span>{{ queryData.deviceStatus }}</span>
</div>
I have web application writed in React JS and Java Spring boot. In my Board Component I have form with textarea and button. While debugging when I click on button I am redirect to PostMapping in UserController spring project. My method has one parameter. It's #RequestBody String query.
I get text from textarea in HTML character codes in hex code. I need to plain text from this String.
I get something what look like this:
CREATE+TABLE+users+%28%0A%09id+INT%2C%0A%09fullName+VARCHAR%28220%29+NOT+NULL%2C%0A%09city+VARCHAR%28120%29+NOT+NULL%2C%0A%09country+VARCHAR%2860%29+NOT+NULL%2C%0A%09PRIMARY+KEY%28id%29%0A%29%3 ...
where + does mean space
I was trying resolve this problem.
Nothing works.
First way:
byte[] s = DatatypeConverter.parseHexBinary(query);
System.out.println(new String(s, "UTF-8"));
Second way:
Apache Commons Codec - Hex
byte[] bytes = Hex.decodeHex(query.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Here is my code
Spring project:
UserController class
#Controller
#RequestMapping("fiddle")
public class MainController {
#PostMapping
public ResponseEntity<?> processingQueries(#RequestBody String query) {
System.out.println(query);
return new ResponseEntity<String>("Query prcessed successfully.", HttpStatus.OK);
}
}
React JS project:
Board component
import React from 'react';
import TableButton from './TableButton';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { processQueries } from '../actions/queryActions';
class Board extends React.Component {
constructor() {
super();
this.state = {
query: 'Write here your SQL query...'
}
this.onChange = this.onChange.bind(this);
this.resetField = this.resetField.bind(this);
this.onSubmitRun = this.onSubmitRun.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
resetField(e) {
this.setState({ query: '' });
}
onSubmitRun(e) {
e.preventDefault();
console.log(this.state.query);
this.props.processQueries(this.state.query, this.props.history);
}
render() {
return (
<div className="box flex-stretch">
<div className="blue smallClass">
<TableButton />
</div>
<div className="mediumClass">
<form onSubmit={this.onSubmitRun}>
<textarea
name="query"
className="txtArea"
value={this.state.query}
onChange={this.onChange}
onClick={this.resetField}
rows="27"
>
Write here your SQL queries...
</textarea>
<input type="submit" value="Run" className="runButton"/>
</form>
</div>
<div className="red largeClass">
One of three columns
</div>
</div>
);
}
}
Board.propTypes = {
query: PropTypes.string
}
const mapStateToProps = state => ({
query: state.query
})
export default connect(mapStateToProps, { processQueries })(Board);
queryReducer
import { PROCESS_QUERY } from '../actions/types';
const initialState = {
query: ''
}
export default function(state = initialState, action) {
switch(action.type) {
case PROCESS_QUERY:
return {
...state,
query: action.payload
}
default:
return state;
}
}
queryActions
import axios from 'axios';
import { GET_ERRORS, PROCESS_QUERY } from './types';
export const processQueries = (query, history) => async dispatch =>
{
try {
console.log(query);
await axios.post("/fiddle", query);
history.push("/fiddle");
dispatch({
type: PROCESS_QUERY,
payload: ''
})
} catch(error) {
dispatch({
type: GET_ERRORS,
payload: error.response.data
})
}
}
I need to convert this string from textarea to plain text. Data inserted to textarea are plan SQL queries.
All you need to decode string with UrlDecoder.
String result = java.net.URLDecoder.decode(query, StandardCharsets.UTF_8.displayName());
I am trying to upload a photo in my React application, along with some form data. It works with uploading form data from ItemAdd.jsx, a child component of ItemList.jsx. However, when I try to also POST an image file with this data, the image property is undefined when it hits the server.
My suspicion is that I'm using the wrong content-type in the request, but I'm not sure what I should be using instead (if that is the issue here).
Parent Component - ItemList.jsx
import React from 'react';
import 'whatwg-fetch';
import classNames from 'classnames';
import ItemAdd from './ItemAdd.jsx';
export default class ItemList extends React.Component {
constructor() {
super();
this.createItem = this.createItem.bind(this);
}
createItem(newItem) {
console.log('PHOTO:', newItem.image);
fetch('/api/item', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newItem),
}).then(response => {
}).catch(err => {
});
}
render() {
return (
<div>
<ItemAdd createItem={this.createItem} />
</div>
);
}
}
Child Component - ItemAdd.jsx
import React from 'react';
export default class ItemAdd extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
image: null,
imagePreviewUrl: null
}
}
handleSubmit(e) {
e.preventDefault();
let form = document.forms.itemAdd;
this.props.createItem({
name: form.name.value,
image: this.state.image
});
// Clear the form and state for the next input.
form.name.value = "";
this.state.image = null;
this.state.imagePreviewUrl = null;
}
handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
image: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
let { imagePreviewUrl } = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} className={'img-preview'} />);
} else {
$imagePreview = (<div className="previewText">Please select an image.</div>);
}
return (
<div>
<form name="itemAdd" onSubmit={this.handleSubmit}>
<table>
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" name="name" id="name" placeholder="Name" /></td>
</tr>
<tr>
<td><input type="file" onChange={(e) => this.handleImageChange(e)} /></td>
<td>
<div className="img-preview">
{$imagePreview}
</div>
</td>
</tr>
<tr>
<td><button>Add</button></td>
</tr>
</table>
</form>
</div>
);
}
}
You might not be able to post an image as part of JSON data, calling JSON.stringify() on an image is not a good idea.
I would recommend using formData to submit the form, which makes it multipart/form-data content type.
You might have to handle that differently in the backend.
Example :
createItem(newItem) {
console.log('PHOTO:', newItem.image);
const h = {}; //headers
let data = new FormData();
data.append('image', newItem.image);
data.append('name', newItem.name);
h.Accept = 'application/json'; //if you expect JSON response
fetch('/api/item', {
method: 'POST',
headers: h,
body: data
}).then(response => {
// TODO : Do something
}).catch(err => {
// TODO : Do something
});
}
You can read more on formData
I'm trying to make an upload function for uploading file/image to my firebase database storage. I have already paste the correct API key in the environment.ts and import it to app.module.ts like AngularFireModule.initializeApp(environment.firebaseConfiguration, 'app-root'). I made the push string properties function and upload file function separately. The other properties like name and description are pushed correctly into my Firebase real-time database but the file is not uploaded to the storage so i also cant obtain the url.
//product.ts
export class Product {
$prdKey: string;
prdName: string;
prdImage ? : File;
imageURL ? : any;
prdDescription: string;
constructor(prdImage: File) {
this.prdImage = prdImage;
}
}
//product.service.ts
Product: any;
selectedProduct: Product = new Product(this.Product);
currentFileUpload: Product;
insertProduct(Product: Product) {
this.productList.push({
prdName: Product.prdName,
prdDescription: Product.prdDescription
});
}
private basePath = '/';
pushFileToStorage(Product: Product) {
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`${this.basePath}/${Product.prdImage.name}`).put(Product.prdImage);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot) => {
// in progress
const snap = snapshot as firebase.storage.UploadTaskSnapshot
},
(error) => {
// fail
console.log(error)
},
() => {
// success
Product.imageURL = uploadTask.snapshot.downloadURL
Product.prdName = Product.prdImage.name
this.saveFileData(Product)
}
);
}
private saveFileData(Product: Product) {
this.firebase.list(`${this.basePath}/`).push(Product);
}
//product.component.ts
onSubmit(form: NgForm) {
if (form.value.$prdKey == null) {
this.ProductService.insertProduct(this.ProductService.selectedProduct);
} else {
this.ProductService.updateProduct(this.ProductService.selectedProduct);
}
}
upload() {
const file = this.ProductService.selectedProduct.prdImage
this.ProductService.currentFileUpload = new Product(file);
}
selectFile(event) {
this.ProductService.selectedProduct = event.target.files;
}
<!--product.component.html-->
<form #productForm="ngForm" (ngSubmit)="onSubmit(productForm); upload()">
<!--skip name and descrioption input-->
<label>Upload an Image</label>
<input type="file" class="form-control">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Can anyone help me solve this? Please let me know of more snippets are needed. Thank you in advance.
I'm having troubles inserting data to MySQL from Express API Server, I'm getting the data from my React Client. I have 4 fields and one of them is not inserting correctly, you can see it in the below screen (the last 3 rows).
This is my client (React) code.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {datos: {}};
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e){
e.preventDefault();
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch('/todo/meterla',{
method: 'POST',
data:{
task: self.refs.task
}
})
.then(function(response){
return response.json()
}).then(function(body){
console.log(body);
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="TASK" ref="task"/>
<input type="submit"/>
</form>
</div>
);
}
}
export default App;
This is mi server code:
// Add a new todo
app.post('/todo/meterla', function (req, res) {
var task = req.body;
var query = mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
});
});
In the client code, change data to body in the onSubmit handler:
fetch('/todo/meterla',{
method: 'POST',
body:{
task: self.refs.task
}
})
In the server code, change this line var task = req.body; to var task = req.body.task;.