pass the value of a uploaded file photo in vuejs and Laravel - laravel

I want to upload my photo and pass the value to the laravel. I have this edit profile which my photo be uploaded. Now my problem is how will i able to pass the value of the photo to axios. Here is my code below
<template>
<div class="card">
<div class="card-header">Profile Form</div>
<div class="card-body">
<div class="container">
<div class="row">
<div class="col-sm">
<div v-show="updatePP" id="preview">
<img v-if="url" :src="url" />
</div>
<div v-show="pp" v-if="editProfile.profile_pic == NULL">
<img src="https://i.imgflip.com/4/d0tb7.jpg" />
</div>
<div v-else>
asasasas
</div>
</div>
<div class="col-sm">
<form #submit.prevent="formSubmit" enctype="multipart/form-data">
<div class="form-group">
<div class="form-row" >
<div class="col-lg-12">
<label>First Name:</label>
<br>
<input type="text" id="name" name="name" class="form-control" v-model="editProfile.name" />
</div>
<div class="col-lg-12">
<label>Last Name:</label>
<br>
<input type="text" id="lastName" name="lastName" class="form-control" v-model="editProfile.last_name" />
</div>
<div class="col-lg-12">
<label>Address:</label>
<br>
<input type="text" id="address" name="address" class="form-control" v-model="editProfile.address" />
</div>
<div class="col-lg-12">
<label>Upload Profile:</label>
<br>
<input type="file" id="photo" name="photo" #change="onFileChange" />
</div>
<div class="col-lg-12">
<br>
<br>
<button type="submit" class="btn btn-success btn-lg">Update</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return{
editProfile:{
userId: this.$userId,
},
url: null,
pp: true,
updatePP: false,
userId:this.$userId,
}
},
mounted(){
const url = window.location.href;
const id = url.split("/").slice(4)[0];
this.getEditProfile(id);
},
methods:{
onFileChange(e){
const file = e.target.files[0];
this.url = URL.createObjectURL(file);
this.editProfile.photo = file;
this.updatePP = true;
this.pp = false;
},
formSubmit(){
const ids = this.userId;
let currentObj = this;
alert(this.editProfile.name);
alert(this.editProfile.last_name);
alert(this.editProfile.address);
alert(this.editProfile.photo.name);
let formData = new FormData();
formData.append('photo', this.editProfile.photo.name);
formData.append('name', this.editProfile.name);
formData.append('lastName', this.editProfile.last_name);
formData.append('address', this.editProfile.address);
console.log(formData.values);
axios.put(`/api/profile/${ids}/update`, this.editProfile).then(response=>{
console.log(response.data);
currentObj.success = response.data.success;
}).catch(error=>{
console.log(error);
currentObj.output = error;
});
},
updateProfile(id){
},
getEditProfile(id){
axios.get(`/api/profile/${id}/edit`).then(response=>{
this.editProfile = response.data;
console.log(response.data);
});
}
}
}
</script>
<style scoped>
#preview {
display: flex;
justify-content: center;
align-items: center;
}
#preview img {
max-width: 250px;
max-height: 250px;
}
</style>
i am using the FormData() and i want the data to be pass to axios.
Any help is muchly appreciated. TIA

You need to include the file's input field and submit the FormData object you are creating.
Change your submit() function to something like this and HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to sprrof it and add a hidden _method field to the form (https://laravel.com/docs/8.x/routing#form-method-spoofing):
formSubmit(){
const ids = this.userId;
let currentObj = this;
alert(this.editProfile.name);
alert(this.editProfile.last_name);
alert(this.editProfile.address);
alert(this.editProfile.photo.name);
let formData = new FormData();
formData.append('photo', this.editProfile.photo.name);
formData.append('name', this.editProfile.name);
formData.append('lastName', this.editProfile.last_name);
formData.append('address', this.editProfile.address);
formData.append('file', document.getElementById('fileInputId').files[0]);
console.log(formData.values);
axios.post(`/api/profile/${ids}/update`, formData).then(response=>{
console.log(response.data);
currentObj.success = response.data.success;
}).catch(error=>{
console.log(error);
currentObj.output = error;
});
},
Then to use put, add this to your form: <input type="hidden" name="_method" value="PUT">.
In your controller you can check to see if the file came through successfully with something like:
public function controllerMethod(Request $request)
{
if($request->hasFile('file')) {
dd('Success - there is a file.');
}
dd('Unsuccessful - there is no file');
}
This questions may help: How to send a file via Axios to Laravel

Related

Using Vue, Inertia, Laravel, how do I update a file object in an edit component?

I currently have an edit page, which hits an update function to update the Itinerary object when changed.
On this page, if I click submit straight away, and dd() the $request from the ItineraryController, it returns all of the existing form data, as expected.
If I edit the data in the fields, then submit it, it returns successfully with a full request object as expected.
If, however, I choose a file in the "replace file" selector, the entire request object shows as null when the form is submitted, and thus can't be submitted.
How can I adjust this so that the "replace file" input is operational, and fills the request object with the existing itinerary data?
Component:
<template>
<form #submit.prevent="submit">
<div class="row w-75 m-auto">
<h1>Edit Itinerary</h1>
<div class="col-md-6">
<label for="title">Title</label>
<input v-model="form.title" class="form-control" name="title" placeholder="Itinerary Title" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="gen_narrative">Narrative</label>
<textarea v-model="form.gen_narrative" class="form-control" name="gen_narrative" placeholder="Itinerary Narrative"></textarea>
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label>Current Photo</label>
<img :src="assetUrl(props.itinerary.f_photo)" alt="featured photo" />
</div>
</div>
<br />
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="fileChange" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="authorid">Author Name</label>
<input v-model="form.authorid" class="form-control" name="authorid" placeholder="Author Name" type="text" />
</div>
</div>
<div class="row w-75 m-auto">
<div class="col-md-6">
<button class="btn btn-primary" type="submit">Edit Itinerary</button>
</div>
</div>
</form>
</template>
<script setup>
import { useForm } from "#inertiajs/inertia-vue3";
function assetUrl(path) {
return process.env.MIX_BASE_URL + "storage/" + path;
}
function fileChange(event) {
form.f_photo = event.target.files[0];
}
let props = defineProps({
itinerary: {
type: Object,
required: true,
},
});
let form = useForm({
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops,
});
let submit = () => {
console.log(form.title);
form.patch("/itineraries/" + props.itinerary.id);
form.reset();
};
console.log(form);
</script>
<style scoped></style>
Controller:
public function edit($id)
{
$itinerary = Itinerary::find($id);
return Inertia::render('Itineraries/Edit', [
'itinerary' => $itinerary,
]);
}
public function update(Request $request, $id)
{
$itinerary = Itinerary::find($id);
$itinerary->title = $request->title;
$itinerary->gen_narrative = $request->gen_narrative;
//upload the photo
if ($request->hasFile('f_photo')) {
$itinerary->f_photo = $request->f_photo->store('public/itinerary_photos');
}
$itinerary->authorid = $request->authorid;
$itinerary->save();
return redirect('/itineraries');
}
let form = useForm({
forceFormData: true,
title: props.itinerary.title,
gen_narrative: props.itinerary.gen_narrative,
f_photo: null,
authorid: props.itinerary.authorid,
stops: props.itinerary.stops
})
The best I can come up with is writing your file upload inline
<div class="row w-75 m-auto">
<div class="col-md-6">
<label for="f_photo">Replace Photo</label>
<input class="form-control" name="f_photo" type="file" #input="form.f_photo = event.target.files[0]"/>
</div>
</div>
Based on this example in official documentation you can do
<input type="file" #input="form.f_photo = $event.target.files[0]" />
Your issue is probably because Inertia does not natively support uploading files using a multipart/form-data request for the put, patch or delete methods, as is stated here (in the "Multipart limitations" section).
An alternative way is to submit without form helper using post method with the _method attribute of 'put', like:
Inertia.post("/itineraries/" + props.itinerary.id", {
_method: 'put',
f_photo: form.f_photo,
})

POST http://127.0.0.1:8000/ 422 (Unprocessable Content)

I have an error on login form after upgrading version Vue JS, Axios, Laravel.
This project code working well with old version. Anyone can explain this serious errors.
Thanks you for your help!
And I stuck with it many days. I've search for similar post error, but only seen this(POST http://127.0.0.1:8000/ 422 (Unprocessable Entity)).
<template>
<div class="back-img" :style="`background-image: url('${appUrl}/images/background/default-background.jpg')`">
<div class="container-fluid">
<div class="row">
<div class="col-12 col-md-6 offset-md-6 col-lg-4 offset-lg-8 col-xl-4 offset-xl-8 pl-0">
<div class="sign-in-sign-up-content">
<form class="sign-in-sign-up-form">
<div class="text-center mb-4 application-logo">
<img :src="publicPath+'/uploads/logo/'+appLogo" alt="" class="img-fluid logo">
</div>
<div class="form-row">
<div class="form-group col-12">
<h3 class="text-center mb-0">
{{ trans('lang.hi_there') }}
</h3><br>
<label class="text-center d-block">
{{ trans('lang.sign_in_to_your_dashboard') }}
</label>
</div>
</div>
<div v-if="alertMessage.length>0" class="alertBranch">
<div class="alert alert-warning alertBranch" role="alert">
{{alertMessage}}
</div>
</div><br>
<div class="form-row">
<div class="form-group col-12">
<label for="username" style="font-size: 20px;"> {{ trans('lang.login_username') }}</label>
<input id="username"
v-validate="'required'"
v-model="username"
type="text"
name="username"
class="form-control"
:placeholder="trans('lang.enter_username')"
:class="{ 'is-invalid': submitted && errors.has('username') }">
<div class="heightError" v-if="submitted && errors.has('username')">
<small class="text-danger" v-show="errors.has('username')">
{{ errors.first('username') }}
</small>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-12">
<label for="password" style="font-size: 20px !important;">{{ trans('lang.login_password') }}</label>
<input id="password"
v-validate="'required'"
ref="password"
v-model="password"
name="password"
type="password"
class="form-control"
:placeholder="trans('lang.enter_password')"
:class="{ 'is-invalid': submitted && errors.has('password') }">
<div class="heightError">
<small class="text-danger" v-show="errors.has('password')">
{{ errors.first('password') }}
</small>
</div>
</div>
</div>
<div class="form-row loginButton">
<div class="form-group col-12">
<common-submit-button class="btn-block text-center auth-button"
style="font-size: 20px !important;"
:buttonLoader="buttonLoader"
:isDisabled="isDisabled"
:isActiveText="isActiveText"
buttonText="login"
v-on:submit="loginPost"/>
</div>
</div>
<!-- <div class="form-row">
<div class="form-group col-12">
<a href="#"
#click="forgetPassword"
class="bluish-text">
<i class="fa fa-lock"/>
{{ trans('lang.forgot_password') }}
</a>
</div>
</div> -->
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axiosGetPost from '../../helper/axiosGetPostCommon';
export default {
extends: axiosGetPost,
props: ['checkusername', 'checkpass'],
data() {
return {
username: this.checkusername,
name: '',
password: this.checkpass,
remember: true,
buttonLoader: false,
isActiveText: false,
isDisabled: false,
preLoaderType: 'load',
hidePreLoader: false,
isActive: 'active',
alertMessage: '',
submitted: false,
}
},
methods: {
loginPost() {
this.submitted = true,
this.$validator.validateAll().then((result) => {
if (result) {
this.inputFields = {
username: this.username,
password: this.password,
};
this.buttonLoader = true;
this.isDisabled = true;
this.isActiveText = true;
this.loginPostMethod('/', {
username: this.username,
password: this.password,
}
);
}
});
},
forgetPassword() {
let instance = this;
instance.redirect('/password/reset');
},
loginPostSucces(response) {
let instance = this;
instance.redirect("/sales");
},
loginPostError(response) {
let instance = this;
instance.buttonLoader = false;
instance.isDisabled = false;
instance.isActiveText = false;
instance.alertMessage = response.data.errors.username[0];
},
}
}
</script>
File: resources\assets\js\js\bootstrap.js
window._ = require('lodash');
window.Popper = require('popper.js').default;
import axios from "axios";
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
if (document.querySelector('meta[name="csrf-token"]')) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
}
You have to pass the csrf token in Ajax request.
data: {
"_token": "{{ csrf_token() }}",
other form data
}
OR
You can create csrf token in header using meta element and access that value in while sending ajax request.
<meta name="csrf-token" content="{{ csrf_token() }}" />
// Access in ajax request like below
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
Laravel + Vue + Axios
Laravel has configurd the default token header in resources/js/bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
So you have to just import axios like.
import axios from 'axios';

I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields to Controller

$("#addRow").click(function ()
{
#{
new VLSM_Model().LansValues.Add(new Lans());
}
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
html += '<input type="number" id="[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $(this).serializeArray();
$.ajax(
{
type: "POST", //HTTP POST Method
url: "VLSM_Controller/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br/>
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br/>
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Calculate VLSM" class="btn btn-info" id="createButton"/>
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
I created dynamically input fields as you can see from code, but I have difficulties to pass the data to controller, and to use the data for calculations inside the controller.
My question is how to pass data from dynamically created input fields with ajax to controller and how to use passed data for any kind of calculations.
Model binding system will look through the property by name. So you need match the name attribute in html with model property name. That is to say, your dynamic added input fields should have name attribute:name="LansValues[index].InitialLanValues".
Here is a whole working demo:
Model:
public class VLSM_Model
{
public string IP_Address { get; set; }
public List<Lans> LansValues { get; set; }
public int cidrValue { get; set; }
}
public class Lans
{
public int InitialLanValues { get; set; }
}
View:
Modify type="submit" to type="button", otherwise the ajax will not hit.
#model VLSM_Model
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br />
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br />
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br />
<div class="form-group">
#*change here*#
<input type="button" value="Calculate VLSM" class="btn btn-info" id="createButton" />
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
JS:
Change the dynamic html to name="LansValues[' + (rowCount - 1) + '].InitialLanValues" and change var inputData = $(this).serializeArray(); to var inputData = $('form').serializeArray();.
#section Scripts
{
<script>
$("#addRow").click(function ()
{
#*#{new VLSM_Model().LansValues.Add(new Lans());}*#
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
//change id attribute to name attribute and modify the name
html += '<input type="number" name="LansValues[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $('form').serializeArray(); //change here...
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
public IActionResult Create(VLSM_Model model)
{
//...
}
}
Note:
Actually if you just use form submit, it also can work well. If you use form submit, just change your original code:name="LansValues[' + (rowCount - 1) + '].InitialLanValues" in $("#addRow").click() function. Then remove the $("#createButton").click() function. No need change any other code.

I am using websocket to send images in a chat with spring boot and STOMP client with js

Hello everyone I am using websocket to send images using stomp client and am facing this error:
Uncaught TypeError: Cannot read property 'files' of null
at sendMyImage (app.js:46)
at HTMLButtonElement.<anonymous> (app.js:68)
at HTMLButtonElement.dispatch (jquery.js:5201)
at HTMLButtonElement.q.handle (jquery.js:5009)
sendMyImage # app.js:46
(anonymous) # app.js:68
dispatch # jquery.js:5201
q.handle # jquery.js:5009
This is the code that am using in my index.html
<html>
<head>
<title>chat app</title>
<link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/main.css" rel="stylesheet">
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
<script src="/app.js"></script>
</head>
<body>
<div id="main-content" class="container">
<div class="row">
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="connect">WebSocket connection:</label>
<button id="connect" class="btn btn-default" type="submit">Connect</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="participantId">ParticipantId :</label>
<input type="number" id="participantId" class="form-control" placeholder="Your id here...">
</div>
<div class="form-group">
<label for="id">Content :</label>
<input type="text" id="content" class="form-control" placeholder="Your message content here...">
</div>
<button id="send" class="btn btn-default" type="submit">Send</button>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label>Select an image and hit send:</label>
<input type="file" id="file" accept="image/*"/>
<button id="sendImage" class="btn btn-default" type="submit">Send Image</button>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="conversation" class="table table-striped">
<thead>
<tr>
<th>chatmessages</th>
</tr>
</thead>
<tbody id="chatmessages">
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
and this is my app.js code :
var stompClient = null;
const messageWindow = document.getElementById("messages");
const fileInput = document.getElementById("file");
const sendImageButton = document.getElementById("sendImage");
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#chatmessages").html("");
}
function connect() {
var socket = new SockJS('/ws');
socket.binaryType = "arraybuffer";//heere
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/chatmessages', function (chatmessage) {
showChatMessage(JSON.parse(chatmessage.body));
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendParticipantIdAndContent() {
stompClient.send("/app/chat", {}, JSON.stringify({'participantId': $("#participantId").val(),'content': $("#content").val()}));
}
function sendMyImage() {
let file = fileInput.files[0];
sendMessage(file);
fileInput.value = null;
}
function showChatMessage(message) {
$("#chatmessages").append("<tr><td>" + message.message + "</td></tr>");
}
function addImageToWindow(image) {
let url = URL.createObjectURL(new Blob([image]));
messageWindow.innerHTML += `<img src="${url}"/>`
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendParticipantIdAndContent(); });
$( "#sendImage" ).click(function() { sendMyImage(); });
});
I really want to know what is the problem because i didn't get why he would be reading the file as a null.
Please tell me where did i mess up
and thank you
The problem is because the fileInput in your javascript is read as null.
you could try something like this
<input type="file" id="file" >
and access content like this
let file = document.getElementById("file").files[0];
And the problem here is definitely not related stomp or spring or websocket.

cannot insert data into vue select sent from laravel

This is the vuejs component for editing song info. the problem here is with tags.I cannot show the tags of the song in vue select for editing.
<template>
<div>
<a data-toggle="modal" :data-target="'#EditModal'+ modalid" #click="select(song)"><span title="edit" class="glyphicon glyphicon-pencil" ></span></a>
<a class=""><span title="delete" class="glyphicon glyphicon-trash"></span></a>
<!-- Modal for editing song tracks-->
<div class="modal fade" :id="'EditModal'+ modalid" tabindex="-1" role="dialog" aria-labelledby="EditModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="EditModalLabel">Edit Song</h5>
<button type="button" class="close" ref="closemodal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form ref="uploadform">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<div class="col-md-5">
<button type="button" #click="browseImage" class="btn btn-md btn-default">Choose image:</button>
<div id="image_previews">
<img ref='image' class="" v-bind:src="image" width="200px" height="200px" >
<input class="form-control-file" ref="imageinput" type="file" name="feature_image" #change="showImage($event)">
</div>
</div>
<div class="col-md-7">
<div class="form-group">
<label for="title">Song Title:</label>
<input type="text" v-model="esong.title" class="form-control" required maxlength="255">
</div>
<div class="form-group">
<label for="genre"> Genre (tag atleast one) </label>
<v-select :placeholder="'choose tag'" v-model="tagids" label="name" multiple :options="tags"></v-select>
</div>
<div class="form-group">
<label for="upload_type">Song Upload Type</label>
<select name="upload_type" v-model="esong.upload_type" class="form-control">
<option value="public">public( free )</option>
<option value="private">private( for sale )</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Description:</label>
<textarea class="form-control" id="message-text" v-model="esong.song_description"></textarea>
</div>
<div class="form-group" v-if="private">
<label for="upload_type">Song price</label>
<input type="text" v-model="esong.amount" class="form-control" required maxlength="255">
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" #click="edit">Save</button>
</div>
</div>
</div>
</div><!-- end of modal -->
</div>
</template>
<script>
import vSelect from 'vue-select'
export default {
props: ['song','modalid','index','tags'],
components: {vSelect},
mounted() {
},
watch: {
tagids() {
console.log('changed tagids value');
// this.value = this.tagsid;
}
},
computed: {
private() {
if(this.esong.upload_type == 'private') {
return true;
}
return false;
},
},
methods: {
select(song) {
console.log(song.title);
this.getTagIds(song);
},
edit() {
let formData = new FormData();
formData.append('title', this.esong.title);
formData.append('img', this.esong.img);
formData.append('description', this.esong.song_description);
formData.append('upload_type', this.esong.upload_type);
formData.append('amount', this.esong.amount);
formData.append('tags', JSON.stringify(this.tagids));
formData.append('_method', 'PUT');
axios.post('/artist/songs/' + this.esong.id, formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response =>{
this.$refs.closemodal.click();
toastr.success('successfully edited song.');
this.$emit('update', {song:this.esong,index:this.index});
}).catch(error => {
console.log(error);
});
},
getTagIds(song) {
axios.post('/gettagids', song ).then(response =>{
this.tagids = response.data;
}).catch(error =>{
console.log(error);
});
},
browseImage() {
this.$refs.imageinput.click();
},
showImage(event) {
this.esong.img = event.target.files[0];
this.image = URL.createObjectURL(event.target.files[0]);
}
},
data() {
return {
esong: this.song,
tagids: {id:'', name:'', label:''},
name:'name',
image:this.song.image
}
}
}
</script>
<style scoped>
input[type="file"] {
display: none;
}
#image_previews {
border-radius: 5px;background-color: whitesmoke; width: 200px; height: 200px;
}
.btn{
border-radius: 0px;
}
</style>
here I cannot get the selected value that was inserted in my table. I wanted to show the tagged values for a song. I am able to get all object of tagged songs from axios post request but v-select doesn't shows the selected value retrieved from a table.
the object received from laravel is similar to the object provided in options which work well with v-select..but it doesn't show the same structure object provided to v-model..or should I provide other props. the document for vue select has not mentioned any of these things

Resources