以下是使用Vue CLI创建的Vue项目,结合Element UI来实现文件上传功能的完整示例。
步骤
- 创建Vue项目:确保你已经安装了Vue CLI,若未安装,可使用以下命令安装:
npm install -g @vue/cli
然后创建一个新的Vue项目:
vue create element-file-upload-demo
cd element-file-upload-demo
- 安装Element UI:在项目根目录下执行以下命令安装Element UI:
npm install element-ui -S
- 配置Element UI:在
src/main.js
中引入Element UI:
import Vue from 'vue';
import App from './App.vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
new Vue({
render: h => h(App),
}).$mount('#app');
- 编写后端接口(使用Spring Boot):后端代码和之前的示例相同,这里再给出一遍。
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
Map<String, Object> result = new HashMap<>();
if (file.isEmpty()) {
result.put("success", false);
result.put("message", "上传的文件为空");
return result;
}
try {
String filePath = "upload/" + file.getOriginalFilename();
File dest = new File(filePath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
result.put("success", true);
result.put("message", "文件上传成功");
} catch (IOException e) {
result.put("success", false);
result.put("message", "文件上传失败:" + e.getMessage());
}
return result;
}
}
编写前端组件(Vue):在
src/components
目录下创建FileUpload.vue
组件:在
App.vue
中使用组件:
<template>
<div id="app">
<FileUpload />
</div>
</template>
<script>
import FileUpload from './components/FileUpload.vue';
export default {
name: 'App',
components: {
FileUpload
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
运行项目
- 启动Spring Boot项目。
- 在Vue项目根目录下执行
npm run serve
启动前端项目。 - 打开浏览器访问
http://localhost:8080
,即可看到文件上传界面。