SpringBoot + Vue 实现文件的上传与下载

本文详细介绍了如何使用SpringBoot后端结合Vue前端实现文件的上传与下载功能。通过ElementUI的Upload组件和Axios,配合后台SpringBoot的处理,实现了文件上传的前端校验、上传与下载操作。同时讨论了如何通过http-request方法处理上传失败的提示,以及使用before-upload方法优化用户体验。
摘要由CSDN通过智能技术生成


1. 前言

简要地记录下 SpringBoot 与 Vue 实现文件的上传与下载


2. 简单案例

2.1 功能需求

前台使用 ElementUI 的 Upload 组件或者是 Axios,后台使用 SpringBoot 来实现文件的上传与下载

2.2 开发环境

  • IDEA-2019.1
  • SpringBoot-2.0.2.RELEASE
  • Maven-3.5.3
  • HBuilderX

2.3 编写代码

2.3.1 上传、下载

2.3.1.1 前端

使用 ElementUI 的 Upload 组件
我这里在 html 页面引入:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="./js/vue.min.js"></script>
		<link rel="stylesheet" href="./css/index.css">
		<script src="./js/index.js"></script>
	</head>
	<body>
		<div id="app">
			<div style="top:100px;width:300px">
				<el-form ref="upload" :model="form" label-width="120px">
					<el-form-item label="请输入文件名" required>
						<el-input v-model="form.fileName" auto-complete="off" class="el-col-width"></el-input>
					</el-form-item>

					<el-form-item>
						<el-button size="small" type="primary" @click="handleDownLoad">下载</el-button>
					</el-form-item>

					<el-form-item>
						<el-upload class="upload-demo" :action="uploadUrl" :before-upload="handleBeforeUpload" :on-error="handleUploadError"
						  multiple :limit="5" :on-exceed="handleExceed" :file-list="fileList" :on-success="onSuccess">
							<el-button size="small" type="primary">点击上传</el-button>
							<div slot="tip" class="el-upload__tip">不超过10Kb</div>
						</el-upload>
					</el-form-item>

				</el-form>
			</div>
		</div>
	</body>

	<script type="application/javascript">
		var app = new Vue({
    
			el: '#app',
			data: {
    
				form: {
    
					fileName: 'test.txt'
				},
				// 后台请求url
				uploadUrl: 'http://localhost:8080/file/upload',
				fileList: [],
				isUpload: false
			},
			methods: {
    
				handleExceed(files, fileList) {
    
					this.$message.warning(`当前限制选择 5 个文件,本次选择了 ${
      files.length} 个文件,共选择了 ${
      files.length + fileList.length} 个文件`);
				},
				handleUploadError(error, file) {
    
					this.$notify.error({
    
						title: 'error',
						message: '上传出错:' + error,
						type: 'error',
						position: 'bottom-right'
					})
				},
				handleBeforeUpload(file) {
    
					this.isUpload = file.size / (1024 * 10) <= 1 ? '1' : '0'
					if (this.isUpload === '0') {
    
						this.$message({
    
							message: '上传文件大小不能超过10k',
							type: 'error'
						})
					}
					return this.isUpload === '1' ? true : false
				},
				onSuccess() {
    
					this.$message.success(`上传成功!`)
				},
				handleDownLoad() {
    
					window.location.href = `http://localhost:8080/file/download?fileName=` + this.form.fileName
				}
			}
		})
	</script>
</html>
  • uploadUrl:data 中的属性。指的是上传到后台的地址
  • 主要是 el-upload 标签,当点击“点击上传”按钮时,选择文件后,会自动提交(auto-upload)到后台,auto-upload 属性默认为 true,可修改。

前台页面:

在这里插入图片描述
上传:可以上传多个文件,最多5个,但每次只能上传一个文件,需要上传多次。然后,文件大小不能超过 10 Kb(handleBeforeUpload()方法中有校验)。否则,上传失败。

下载:前端的下载就是通过链接访问后台地址即可。这里的 fileName 是作为一个测试的下载文件,你可以换成其他的文件,只要本地磁盘存在这个文件就行(重点看后台代码逻辑,在下面呢)。

2.3.1.2 后端

后台是一个父子关系的多模块项目。不太熟悉的话,可以参考此博文:
Maven 多模块项目的创建与配置

项目结构图
在这里插入图片描述

父 POM 文件

<?xml version="1.0" encoding="UTF-8"?>
...
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
  </parent>

  <properties>
    <!-- 在properties中统一控制依赖包的版本,更清晰-->
    <lombok.version>1.18.8</lombok.version>
    <junit.test.version>4.11</junit.test.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version
<h3>回答1:</h3><br/>如何实现SpringBoot+Vue文件上传文件上传涉及前端和后端两个方面的实现。 前端的Vue代码: 1. 定义上传文件的模板: ``` <template> <div> <input type="file" @change="handleFileUpload" ref="fileUpload"> <button @click="submitFile">上传文件</button> </div> </template> ``` 2. 在Vue的methods中添加上传文件的方法: ``` methods: { handleFileUpload () { this.file = this.$refs.fileUpload.files[0] }, submitFile () { let formData = new FormData() formData.append('file', this.file) axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { console.log(response.data) }) } } ``` 这个方法中,我们通过FormData对象来将文件对象上传到服务器端。需要注意的是,在axios请求中,我们需要指定Content-Type为multipart/form-data,以便后端能够正确地解析上传文件。 后端的SpringBoot代码: 1. 配置文件上传的Multipart配置 在application.properties文件中添加以下配置: ``` spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB ``` 这个配置指定了上传文件的大小限制,例如,上限设置为10MB。 2. 添加文件上传的Controller ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 将上传文件保存到指定路径下 String filePath = "C:/uploads/" + file.getOriginalFilename(); file.transferTo(new File(filePath)); return "文件上传成功"; } catch (IOException e) { e.printStackTrace(); return "文件上传失败"; } } } ``` 这个Controller中,通过@RequestParam注解来指定上传文件参数名,再通过MultipartFile来获取上传文件。最后,将文件保存到指定的路径下。需要注意的是,保存路径需要在业务中合理设置。 至此,SpringBoot+Vue文件上传实现就完成了。 <h3>回答2:</h3><br/>Spring Boot是一个广受欢迎的Java开发框架,Vue是一款流行的前端开发框架,他们之间的结合可以为用户提供高效、易用的Web应用程序。在其中,文件上传是Web应用程序的必备功能之一。Spring Boot和Vue的结合可使文件上传实现更加轻松快捷。 首先,需要在前端部分使用Vue来创建一个简单的文件上传组件,该组件可以实现文件选择、文件上传以及进度条的显示等功能。可以使用vue-file-upload或者其他类似的第三方库来实现文件上传功能,同时需要在该组件中设置上传API的路径和上传文件名。 然后,需要在后端部分使用Spring Boot来处理上传文件。Spring Boot提供了丰富的文件处理工具和API,可以轻松地实现文件上传。可以使用Spring Boot的MultipartResolver来解析文件上传请求,同时可以使用MultipartFile类来获取上传文件对象。 接着,需要在Spring Boot的Controller中创建一个上传接口用于处理文件上传请求。该接口需要使用@RequestParam注解来获取上传文件对象,并使用MultipartFile类来处理文件上传。同时,还需要设置上传文件的路径,并将上传成功后的文件路径返回到前端。 最后,需要在前端页面使用Vue来处理上传结果。根据上传返回的结果,可以在页面上显示上传成功或者上传失败的提示信息。同时,还可以使用Vue实现进度条的动态更新,用以提醒用户当前的上传状态。 总的来说,Spring Boot和Vue的结合可以实现快速、高效的文件上传功能。借助两个框架提供的强大工具和API,开发者可以轻松地实现文件上传功能,提高Web应用程序的可靠性和用户体验。 <h3>回答3:</h3><br/>SpringBoot是一个基于Spring框架的快速开发微服务的工具,它简化了Spring框架的配置,使开发者可以快速上手。Vue是一款流行的前端框架,它具有高效的组件化开发和数据双向绑定等优点。在实现文件上传功能时,可以结合使用SpringBootVue实现。 首先,需要在SpringBoot的依赖管理文件pom.xml中添加对spring-boot-starter-web和spring-boot-starter-test的引用: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ``` 然后,在SpringBoot的配置文件application.properties中添加文件上传的配置: ``` spring.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB ``` 接下来,在SpringBoot的Controller中编写文件上传接口: ``` @RestController @RequestMapping("/api") @CrossOrigin(origins = "*", maxAge = 3600) public class UploadController { @PostMapping("/upload") public ResponseResult upload(@RequestParam("file") MultipartFile file) { // 处理文件上传业务逻辑 } } ``` 在Vue的组件中,可以使用vue-axios实现文件上传: ``` <template> <div> <input type="file" @change="uploadFile" /> </div> </template> <script> import axios from 'axios'; export default { data() { return { file: null } }, methods: { uploadFile() { let formData = new FormData(); formData.append('file', this.file); axios.post('http://localhost:8080/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data); }) .catch(error => { console.log(error); }) } } } </script> ``` 其中,formData为提交的表单数据,append方法将文件对象添加到表单中。axios.post方法发送POST请求,在请求头中设置Content-Type为multipart/form-data。 总体来说,使用SpringBootVue实现文件上传功能比较简单。通过配置SpringBoot文件上传参数和编写文件上传接口,配合Vue文件上传组件,即可实现文件上传功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值