I created an API with tymon/jwt-auth, I test it on POSTMAN and it works very well, but when I want to consume it with Guzzle I encountered this error :
GuzzleHttp\Exception\ClientException Client error: POST http://localhost/project/public/api/stands/1/images2/ resulted in a
405 Method Not Allowed response: { "message": "The GET method is not
supported for this route. Supported methods: POST.", "exception":
"Symfony\ (truncated...)
Route for API :
Route::post('stands/{id}/images2', 'ImageController#store');
Controller ImageController.php for API :
public function store(Request $request, $id) {
$validator = Validator::make($request->all(),
[
'nom' => 'required|mimes:jpeg,png'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
if ($files = $request->file('nom'))
{
$path = public_path() . '/images/';
$files->move($path, $files->getClientOriginalName() );
$image = new Image();
$image->nom = $files->getClientOriginalName();
// $image->stand_id= $request->stand_id;
$stand = $this->user->stands()->find($id);
if ($stand->images()->save($image)){
return response()->json([
'success' => true,
"message" => "File successfully uploaded"
]);
$image->save();
}
else{
return response()->json([
'success' => false,
'message' => 'Sorry, image could not be added'
], 500);
}
}
}
Form :
<form method="POST" enctype="multipart/form-data" action="{{ route('postImage',request()->route('id')) }}">
{{ csrf_field() }}
{{ method_field("post")}}
<!--begin::Card-->
<div class="card card-custom gutter-b example example-compact">
<div class="card-header">
<div class="card-title">
<h3 class="card-label">
Upload
</h3>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="box-browse" >
<div class="custom-file">
<input type="file" name="nom" class="custom-file-input" id="inputGroupFile01">
</div>
<div class="content-upload">
<i class="fa fa-download" aria-hidden="true"></i>
</div>
<span class="form-text text-muted">Allowed file types: png, jpg,
jpeg.</span>
<!-- <div class="custom-file">
<label class="custom-file-label" for="customFile">Choose
file</label>
</div> -->
</div>
</div>
</div>
</div>
</div>
<!--end::Card-->
<input type="submit" name="submit" value="ok" />
</form>
Controller Admin\ImageController.php that consumes API for upload file :
public function store(Request $request, $id){
$file = $request->file('nom');
$file_path = $file->getPathname();
$file_mime = $file->getMimeType('image');
$file_uploaded_name = $file->getClientOriginalName();
$url = "http://localhost/project/public/api/stands/".$id."/images2/";
$client = new \GuzzleHttp\Client();
try {
$response = $client->post($url,
[
'multipart' => [
[
'name' => 'nom',
'filename' => $file_uploaded_name,
'Content-Type' => 'multipart/form_data',
'contents' => fopen($file_path, 'r'),]
],
'headers' =>
[
'Authorization' => 'Bearer '.Session::get('token'),
'Accept' => 'application/json',
'Content-Type' => 'multipart/form_data',
]
]);
} catch (Exception $e) {
}
the route :
Route::post('/stands/{id}/images2/', 'Admin\ImageController#store')->name('postImage');
Related
im have little problem with clean input after functions complete
Can someone tell me what im do wrong
After functions is complete im try to clean the input
But i dont have any result with this
this is my code in Vue Component
<form role="form">
<div class="card-body">
<div class="form-group">
<label for="file">Upload File</label>
<div class="input-group">
<div class="custom-file">
<input
type="file"
class="custom-file-input"
id="file"
ref="file"
v-on:change="handleFileUpload"
/>
<label class="custom-file-label" for="file">Choose file</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button v-on:click="onClickUploadAccounts" class="btn btn-primary">Upload</button>
<button v-on:click="onClickSetLoader" class="btn btn-primary">Loader</button>
</div>
</form>
methods: {
handleFileUpload(){
this.file = this.$refs.file.files[0]
},
onClickUploadAccounts(){
let formData = new FormData();
formData.append('file', this.file);
this.$store.commit('imports/setIsLoad', true)
axios.post( '/admin-account-import',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(() => {
console.log('SUCCESS!!')
this.$store.commit('imports/setIsLoad', false)
this.file = ''
formData.delete('file')
formData.append('file', this.file = '')
})
.catch(() => {
console.log('FAILURE!!');
});
},
onClickSetLoader()
{
this.$refs.file.files = ''
},
},
You need to set this.file to null. in your data
data: function () {
return {
file: null
}
}
And you can remove in your methods
this.file = ''
formData.delete('file')
formData.append('file', this.file = '')
I'm trying to inline edit an article and submit the values from the form. However, the v-model values are empty on submit.
Check out my code below. So the top form is for new articles only. And in my v-for there's a switch between 'view' and 'edit' mode.
<template>
<div>
<h2>Articles</h2>
<hr />
<form class="mb-3" #submit.prevent="addArticle">
<div class="form-group">
<input class="form-control" placeholder="Title" v-model="article.title" />
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Bodytext" v-model="article.body"></textarea>
</div>
<button type="submit" class="btn btn-light btn-block">Add new</button>
</form>
<hr />
<div class="card card-body mb-2" v-for="article in articles" v-bind:key="article.id">
<template class="article-row" v-if="edit === article.id">
<form #submit.prevent="editArticle">
<div class="form-group">
<input class="form-control" placeholder="Title" v-model="article.title" />
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Bodytext" v-model="article.body"></textarea>
</div>
<!-- <input type="hidden" v-model="article.id" /> -->
<button type="submit" class="btn btn-light btn-block">Update</button>
</form>
</template>
<template v-else>
<h3>{{ article.title }}</h3>
<p v-html="article.body"></p>
<hr />
<div>
<button #click="toggleEditMode(article.id)" class="btn btn-warning">Edit</button>
<button #click="deleteArticle(article.id)" class="btn btn-danger">Delete</button>
</div>
</template>
</div>
</div>
</template>
<script>
export default {
data() {
return {
articles: [],
article: {
id: "",
title: "",
body: ""
},
article_id: "",
edit: false
};
},
created() {
this.fetchArticles();
},
methods: {
fetchArticles(page_url) {
let vm = this;
page_url = page_url || "/api/articles";
fetch(page_url)
.then(res => res.json())
.then(res => {
this.articles = res.data;
vm.makePagination(res.meta, res.links);
})
.catch(err => console.log(err));
},
addArticle() {
console.log(JSON.stringify(this.article));
fetch("/api/article", {
method: "post",
body: JSON.stringify(this.article),
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(data => {
this.article.title = "";
this.article.body = "";
alert("Article added!", "success");
this.fetchArticles();
})
.catch(err => console.log(err));
},
editArticle() {
console.log(JSON.stringify(this.article));
fetch("/api/article", {
method: "put",
body: JSON.stringify(this.article),
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(data => {
alert("Article updated!", "success");
this.fetchArticles();
})
.catch(err => console.log(err));
},
toggleEditMode(article_id) {
this.edit = article_id;
}
}
};
</script>
The console.log(JSON.stringify(this.article)); on the first line of the editArticle function returns an empty object (the default value)... What am i doing wrong?
You need to set the article befeore trying to update it like that:
toggleEditMode(article_id) {
for (let index = 0; index < this.articles.length; index++) {
const article = this.articles[index];
if(article.id === article_id){
this.article = article;
break;
}
}
this.edit = article_id;
}
Fiddle
Using
Laravel 5.7
I'm trying to use dropbox driver to upload images , it works .. but when i want to get the url .. it gives me an error
This driver does not support retrieving URLs
filesystems.php
'disks' => [
'dropbox' => [
'driver' => 'dropbox',
'app_secret' => env('DROPBOX_APP_SECRET'),
'token' => env('DROPBOX_TOKEN'),
],
],
UploadController.php
public function postUpload(Request $request)
{
$user = Auth::user();
$file = $request->file('picture');
$filename=uniqid($user->id."_").".".$file->getClientOriginalExtension();
Storage::disk('dropbox')->put($filename, File::get($file), 'public');
$url = Storage::disk('dropbox')->url($filename);
$user->profile_pic = $url;
$user->save();
$user->profile_pic = $filename;
$user->save();
return view('upload-complete')->with('filename', $filename)->with('url',$url);
}
upload-complete.blade.php
#extends('template')
#section('content')
<div class="container">
<h1>File Uploaded</h1>
<hr />
<div class="text-center">
<img src="{{ $url }}" class="img-rounded" />
</div>
</div>
#endsection
My vue component like this :
<template>
<div class="modal" tabindex="-1" role="dialog">
...
<div class="form-group">
<label for="change-image">Change image</label>
<input type="file" name="replace" v-on:change="changeImage">
</div>
<div class="form-group">
<label for="alt-image">Alt attr</label>
<input type="text" class="form-control" v-model="altImage">
</div>
<div class="checkbox">
<label>
<input type="checkbox" v-model="mainCover"> Set Cover
</label>
</div>
<button type="button" class="btn btn-success" #click="editImageProduct">
Edit
</button>
...
</div>
</template>
<script>
export default{
...
data() { return {altImage: '', mainCover: '', imageChanged: '', image: ''}},
methods: {
editImageProduct(event) {
const payload = {alt_image: this.altImage, main_cover: this.mainCover, image_changed: this.imageChanged}
this.$store.dispatch('editImageProduct', payload)
},
changeImage(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length)
return;
this.createImage(files[0])
this.imageChanged = files[0]
},
createImage(file) {
var image = new Image()
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.image = e.target.result
};
reader.readAsDataURL(file)
},
}
}
</script>
I want to send the parameters to controller. It will go through modules, api, routes and controller
On the controller, I do like this :
public function editImage(Request $request)
{
dd($request->all());
}
When executed, the result like this :
array:5 [
"alt_image" => "test alt"
"main_cover" => true
"image_changed" => []
]
The param image_changed is empty
Whereas on the component, I do console.log, it display the result
When I do console.log(files[0]), the result like this :
How can I solve this problem?
i am trying to use Vue.js global event bus. Here is my code. I checked lots of examples which are working fine but when i try to use the same idea to code for my project it's showing this Error:
Cannot read property '_parent' of undefined(…)
var bus = new Vue()
Vue.component('login', {
template: "#login",
data: function(){
return {
ip:'',
sessiontoken:''
}
},
ready: function(){
this.settoken();
this.getip();
},
methods: {
getencrypteduser:function(){
},
getauthentifications: function(event){
this.$http.get('http://example.com/application/authentification', function(response){
console.log(response);
}, {headers:{'Accept' : 'json',
'Content-Type' : 'application/hal+json',
'Authorization' : 'Basic ' + window.btoa(this.user+':'+this.password)}
});
bus.$emit('createauthentification')
}
}
})
Vue.component('register', {
template: "#register",
data: function(){
return {
ip:'',
sessiontoken:''
}
},
ready: function(){
this.settoken();
this.getip();
},
methods: {
getencrypteduser:function(){
},
created: function(){
bus.$on('createauthentification', function(event){
console.log(moment().format('LLLL'));
var data = {
'_links':{
'type' : {
'href' : 'http://example.com/rest/type/node/authenfication'
}
},
'title':[
{
'value' : 'cccccccc'
}
],
'field_id':[
{
'value' : this.$cookie.get('test')
}
],
'field_ip':[
{
'value' : this.ip
}
],
'field_va':[
{
'value' : 'Basic ' + window.btoa(this.user+':'+this.password)
}
],
'field_expiration':[
{
'value' : '2016-08-01T14:30:00'
}
]
}
this.$http.post('http://example.com/entity/node?_format=hal_json', data, function(response){
console.log(response);
this.$set('success', 'ok');
this.$route.router.go('/');
}, { headers:{ 'Accept' : 'json',
'Content-Type' : 'application/hal+json',
'Authorization' : 'Basic ' + window.btoa(this.user+':'+this.password),
'X-CSRF-Token': this.sessiontoken
}
}).error(function(response)
{
this.$set('message','Désolé, nous ne avons pas réussi à vous authentifier. Réessayez.');
this.$set('error',true);
});
this.$cookie.set('test', 'Hello world!', 1);
console.log(this.$cookie.get('test'));
}.bind(this));
},
settoken: function(){
this.$http.get(apiURL4, function(response){
this.sessiontoken = response;
console.log(response);
});
},
getip: function(){
this.$http.get(apiURLip, function(response){
this.ip = response;
console.log(response);
});
}
}
})
Here is my HTML template:
<template id="login">
<div class="login-box">
<!-- /.login-logo -->
<div class="login-box-body">
<div class="alert" v-bind:class="{ 'alert-success': success, 'alert-danger': error}"v-show="message">{{ message }}</div>
<p class="login-box-msg">Ouvrir une session</p>
<form v-on:submit.prevent="getauthentifications($event)" >
<div class="form-group has-feedback">
<input v-model="user" value="cri" class="form-control" placeholder="Email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input v-model="password" value="Drup8#92:ocell" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
Mot de passe oublié ?<br>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary btn-block btn-flat">Ouvrir une session</button>
</div>
<div class="social-auth-links text-center">
<p>- OU -</p>
</div>
<div class="text-center">
<button href="#!/register" class="btn btn-default btn-block btn-flat">S'inscrire</button>
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
</template>
Please tell me if someone got this kind of error or found a solution.