我正在使用Laravel和Vuejs开发RestFulApi,现在想使用RestfulApi和vuejs上传照片。这是我的示例代码:
<div class="form-group form-group-default float-left required">
<label for="photo">Photo</label>
<input class="file-input" type="file" ref="photo" name="photo" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
photo: null,
}
}
},
methods: {
addFile: function(e){
let that = this;
that.films_info.photo = this.$refs.photo.files[0];
},
saveFilms: function(){
let that = this;
axios.post('/api/films/save_films',that.films_info)
.then(function (response) {
location.reload(true);
})
.catch(function (error) {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
protected function saveFilms(Films $request)
{
if ( $request->photo ) {
$extension = $filmsObj->photo->getClientOriginalExtension();
$request->photo = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$request->photo->move($dir_path, $request->photo);
}
}
在此代码中,我在getClientOriginalExtension()方法调用中遇到错误。它说:
getClientOriginalExtension()方法在字符串上调用。
答案 0 :(得分:1)
最后,我设法通过VueJS和Laravel Api调用解决了照片上传问题。
<div class="form-group form-group-default float-left required">
<label for="file">File</label>
<input class="file-input" type="file" ref="file" name="file" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
file: null,
}
}
},
methods: {
addFile(e){
this.films_info.file = this.$refs.file.files[0];
},
saveFilms(){
let formData = new FormData();
formData.append('file', this.films_info.file);
axios.post('/api/films/save_films',formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
location.reload(true);
})
.catch(error => {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
$dir_path = 'uploads/films/images';
$dir_path_resize = 'uploads/films/images/45x45';
if( $request ){
$filmsObj = new Film();
if (!File::exists($dir_path))
{
File::makeDirectory($dir_path, 0775, true);
}
if (!File::exists($dir_path_resize))
{
File::makeDirectory($dir_path_resize, 0775, true);
}
if ( $request->file ) {
$file = $request->file;
$extension = $file->getClientOriginalExtension(); // getting image extension
$file_name = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$file->move($dir_path, $file_name); // uploading file to given path
// Start : Image Resize
$image = Image::make(public_path($dir_path.'/'.$file_name));
// resize the image to a height of 45 and constrain aspect ratio (auto width)
$image->resize(null, 45, function ($constraint) {
$constraint->aspectRatio();
});
$image->save(public_path($dir_path_resize.'/'.$file_name));
// End : Image Resize
}