Can anyone help me to convert the following code, so instead of putting it in Vue component, I want to put it in script tag in blade. and here is my input tag for uploading file
<input type="file" name="photo" />
Streaming Files To S3
<input type="file" id="file" ref="file">
Vapor.store(this.$refs.file.files[0], {
progress: progress => {
this.uploadProgress = Math.round(progress * 100);
}
}).then(response => {
axios.post('/api/profile-photo', {
uuid: response.uuid,
key: response.key,
bucket: response.bucket,
name: this.$refs.file.files[0].name,
content_type: this.$refs.file.files[0].type,
})
});
I dont knw how to convert the code
Related
All inputs in the form are bind via v-model to the data in the Vue component like this
<validation-provider name="first_name" rules="required" v-slot="{ failed, errors }" :debounce="500">
<input type="text"
id="first_name"
name="first_name"
placeholder="First name"
class="form-control"
:class="{'is-invalid' : failed}"
:disabled="loading"
value="{{ auth()->user()->first_name }}"
tabindex="1"
v-model.trim="user.first_name"
>
<div class="invalid-feedback" v-show="failed">
#{{ errors[0] }}
</div>
v-model doesn't show a default value if there is one value="{{ auth()->user()->first_name }}" so I'm trying to solve this issue like this
data() {
return {
user: {
first_name: document.querySelector("input[name=first_name]").value,
},
loading: false
};
},
But I'm very sure this is not the best way to do this. I've tried looking for an answer, but they are kinda the same. What's the best way to do this?
you have to find a way pass that user information to (vue)js. your solution isnt wrong but in vue.js we work with data or state so my solution is create custom component for this problem like:
// blade
<UserForm :data='#json(auth()->user())' />
// component data
data() {
return {
user: this.data,
loading: false
// and what ever you need
};
},
of course there is a another way and you put user data in window DOM object throw head tag of your blade file. here:
#auth
<script>
window.user = #json(auth()->user())
</script>
#endauth
then you can access it in you components:
data() {
return {
user: {
first_name: window.user.first_name
},
loading: false
};
},
I have created a form where you can upload video files, but I notice that when uploading it, video takes time to upload depending on the size of the file,so to avoid people staring at a screen for a long time waiting for their video to upload I will send them to a page that says "Your video is processing and will be available when ready".The video is indeed saving to the public app folder and also it saves to my aws3 bucket folder as I requested but I noticed that its not saving the file in the database and I don't know why it by passes the database. I am using laravel, ffmpeg to convert and compress videos and ajax. Can someone help me with this. here is my code below
//this the fileupload.blade.php
<div class="container">
<div class="card">
<div class="card-body">
<form method="POST" action="{{ route('fileUploadPost') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input name="file" id="poster" type="file" class="form-control">
<input type="submit" value="Submit" class="btn btn-success">
</div>
</form>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function validate(formData, jqForm, options) {
var form = jqForm[0];
if (!form.file.value) {
alert('File not found');
return false;
}
}
(function() {
$('form').ajaxForm({
uploadProgress: function(event, position, total, percentComplete) {
window.location.href = "complete";
},
success: function() {
},
complete: function(xhr) {
}
});
})();
</script>
//this is the controller
$request->validate([
'file' => 'required',
]);
$viddy=new Video;
$file = $request->file('file');
$fileName =uniqid().$file->getClientOriginalName();
$request->file->move(public_path('/app'), $fileName);
$name_file=uniqid().'video.mp4';
$ffp=FFMpeg::fromDisk('local')
->open($fileName)
->addFilter(function ($filters) {
$filters->resize(new \FFMpeg\Coordinate\Dimension(640, 480));
})
->export()
->toDisk('s3')
->inFormat(new \FFMpeg\Format\Video\X264('libmp3lame'))
->save($name_file);
$imageName = Storage::disk('s3')->url($name_file);
$viddy->title=$imageName;
$viddy->save();
return response()->json(['success'=>'You have successfully upload file.']);
}
I'm was using server side validation with laravel and fecthing the old value in case there was a validation error.
<input type="text" class="form-control" name="nombre" value="{{ old('nombre')}}">
But now I need to validate that input on the client with vue, cause it's required for other stuff.
<input type="text" class="form-control" name="nombre" value="{{ old('nombre')}}" v-model="vNombre" v-on:keyup="validarNombre">
The problem is that when the validation fails on the server side the old input value get's replaced with an empty string cause Vue is initializing that variable. Please help, thanks for reading.
<script type="text/javascript">
var avatar = new Vue({
el: '#validaciones',
data: {
vNombre: '',
validNombre: false,
},
methods: {
validarNombre: function(){
if (this.vNombre == '') {
this.validNombre = false
}
else {
this.validNombre = true;
}
}
}
})
</script>
Since vue is overwriting the field data you can use {{ old('nombre')}} in vNombre vue data field
data: {
vNombre: '{{ old("nombre")}}', //Be careful with single and double quotes
validNombre: false,
},
I get "CLI stopped working" error when i press the upload button.I used the sample code from one of the website to upload file into the database column. I use Laravel 5.2.39. command used: php artisan serve
Code:(Only test version)
Form.blade.php
<form method="post" enctype="multipart/form-data" action="/upload_file">
{{ csrf_field() }}
<input type="file" name="file" />
<input type="submit" name="submit" value="upload" />
</form>
Routes.php
(Not an ideal place to code this but it is only for file upload test purpose)
Route::get('/upload_form', function()
{
$data['files'] = Attachment::get();
return View::make('form', $data);
});
Route::post('/upload_file', function()
{
$rules = array(
'file' => 'required|mimes:doc,docx,pdf',
);
$validator = Validator::make(Request::all(), $rules);
if(Request::hasFile('file'))
{
$f = Request::file('file');
$att = new Attachment;
$att->name = $f->getClientOriginalName();
$att->file = base64_encode(file_get_contents($f->getRealPath()));
$att->mime = $f->getMimeType();
$att->size = $f->getSize();
$att->save();
return Redirect::to('/upload_form');
}
});
Has anyone encountered this issue? Need help.
When i use AJAX request to send multipart/form-data form to server containing picture and 3 text fields, multer process only image, but no text-fields. How to extract text fields from there?
FormData constructor
handleSubmit = () => {
let formData = new FormData(this.refs.productSubmit);
this.props.submitProduct(formData);
}
Form
<form action="javascript:void(0);" onSubmit={this.handleSubmit} ref="productSubmit">
<label> Название </label>
<input className={'form-control'} type="text" name="name" />
<label> Цена </label>
<input className={'form-control'} type="text" name="price" />
<label> Описание </label>
<input className={'form-control'} type="text" name="description" />
<label> Изображение </label>
<input className={'form-control'} type="file" name="picture" style={{height: '100%'}}/>
<hr/>
<button className={'btn btn-warning btn-lg'} bsSize={'small'} type="submit"> Добавить </button>
</form>
Async action creator with AJAX call inside
export function submitProduct(formData) {
return function(dispatch) {
return (
$.ajax({
url: '/addproduct',
method: 'post',
cache: false,
contentType: false,
processData: false,
data: formData,
success: data => {
//dispatch(addedProduct());
},
error: (xhr, status, err) => {
console.error(this.props.url, status, err.toString());
}
})
);
};
}
Server-side request processer
app.post('/addproduct', isLoggedIn, isAdmin, upload.single('image'), (req, res) => {
console.log(req);
console.log(req.body);
console.log(req.file);
});
But req.body is undefined. File is accessable. Fields ARE present in payload request, i can see them with firefox devtools.How to get thoose text fields?
Since Express 4.0 you need to manually add the body-parser middleware, otherwise forms don't get parsed and req.body will be undefined.
In your main file, you should do something like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// ...
module.exports = app;