【发布时间】:2020-09-06 11:10:30
【问题描述】:
我在一个组件中使用 VueJS 构建了一个文件上传表单,我正在使用 axios 并通过一个 post 请求将数据提交到后端(Laravel),我将文件名保存在数据库中。
我正在寻找一种方法来循环浏览已上传的所有文件并在视图中一次显示一个。我希望这将在 Vue 组件内完成,但我不知道是否需要在 laravel 控制器中保存文件后重定向回该组件,或者在 vue 代码中使用“v-for”循环。无论哪种方式,我目前都无法显示列表。
如果在每次上传的旁边看到文件的小图片(徽标)也会很高兴。
Vue 代码:
<template>
<div class="container">
<div class="upload">
<label>File
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
</label>
<button v-on:click="submitFile()">Submit</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
/* Defines the data used by the component */
data(){
return {
file: ''
}
},
methods: {
/* Submits the file to the server */
submitFile(){
/* Initialize the form data */
let formData = new FormData();
formData.append('file', this.file); /* possibly add a validation here to make sure the file variable contains an actual file. */
axios.post('/single-file',
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(){
console.log('SUCCESS!!');
}).catch(function(){
console.log('FAILURE!!');
});
},
handleFileUpload(){
this.file = this.$refs.file.files[0];
/* we set the local file variable to the first File object in the FileList
on the input[type="file"]. The this.$refs.file refers to the ref
attribute on the input[type="file"]. This makes it easily accesible within our component */
}
}
}
</script>
PHP 代码(后端控制器)
<?php
namespace App\Http\Controllers;
use App\File;
use Illuminate\Http\Request;
class SpaController extends Controller
{
public function index()
{
return view('spa');
}
public function store(Request $request)
{
$file = new File();
// read file contents.
$file->name = $request
->files
->get('file')
->getClientOriginalName();
$file->save();
return response()
->json(['success' => 'You have successfully upload a file.']);
}
}
App.js(显示 vue 路由器):
import Vue from 'vue'
import VueRouter from 'vue-router'
window.Vue = require('vue')
Vue.use(VueRouter) // imports and installs the VueRouter plugin
import App from '../views/App' // imports three Vue components
import Hello from '../views/Hello'
import Home from '../views/Home'
const router = new VueRouter({ // constructs a new VueRouter instance that takes a config object
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/hello',
name: 'hello',
component: Hello,
}
],
});
const app = new Vue({ // Make Vue aware of the App component by passing it to the components property in the Vue constructor.
el: '#app',
components: {
App
},
router, // We inject the router constant into the new Vue application to get access to this.$router and this.$route.
});
【问题讨论】:
标签: javascript php laravel vue.js