SpringBoot+Vue3实现上传文件

前言

开发后台系统时经常遇到实现上传文件的功能,在这记录一下我的方法


后端:SpringBoot2
前端:Vue3+ElementPlus
工具:IDEA


一、后端

/**
     * 上传采购合同PDF
     *
     * @author Leo高洋
     * @create 2023-01-20 6:51
     */
    @PostMapping("/uploadContract")
    public Map<String, Object> uploadContract(MultipartFile file) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        if (!file.isEmpty()) {
            logger.info("上传采购合同PDF");
            String originalFilename = file.getOriginalFilename();// 获取文件名称
            String fileName = originalFilename.substring(0, originalFilename.indexOf("."));// 获取前缀
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));// 获取后缀
            String newFileName = fileName + "-" + DateUtil.getCurrentDatePath() + suffixName;// 根据上传时间重新命名合同
            // 根据定义的位置存入合同
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(contractPdfFilePath + newFileName));
            resultMap.put("code", 0);
            resultMap.put("msg", "上传成功");
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("title", newFileName);
            resultMap.put("data", dataMap);
        }
        return resultMap;
    }

此处使用SpringMVC上传文件的MultipartFile工具类,该工具类具体接口方法,此处只演示简单的使用,有兴趣可以查看 MultipartFile工具类(方法详解)这篇文章。
定义方法时,需传入参数,参数类型MultipartFile,我在这里加入判断文件是否为空的操作,可自行修改。

  1. file.getOriginalFilename(); 获取文件的名称
  2. originalFilename.substring(0, originalFilename.indexOf(“.”)); 截取前缀
  3. originalFilename.substring(originalFilename.lastIndexOf(“.”)); 获取后缀,及文件类型
  4. fileName + “-” + DateUtil.getCurrentDatePath() + suffixName; 根据上传时间重新命名文件
  5. FileUtils.copyInputStreamToFile(file.getInputStream(), new File(contractPdfFilePath + newFileName)); 根据定义的位置存入合同

此处的 contractPdfFilePath 为提前定义好的位置,我是在application.yml文件中全局配置,然后在控制器中引入,如下:

application.yml:

contractPdfFilePath: E://2023GraduationDesign/uploadFile/AssetPurchaseContract/

Controller:

@Value("${contractPdfFilePath}")
private String contractPdfFilePath;

配置好便可直接使用,也可以直接在控制器中定义!为了方便前段时间是否上传成功,将文件名称传入Map集合返回前端,即:

Map<String, Object> dataMap = new HashMap<>();
dataMap.put("title", newFileName);

大体流程如上,后端完成!

:此处上传文件有个缺陷,就是选择文件之后立刻上传指定位置,如果在实际应用中发现文件上传错了,重新选择时前文件已在指定文件夹,没有覆盖,个人感觉无伤大雅,但是在前端的回显文件名称时会覆盖新文件名称。

补充:上面代码中在拼接新文件名称时有DateUtil.getCurrentDatePath()方法,是我封装的日期工具类获取当前时间,有兴趣可以自己研究下,这里不过多赘述,代码贴在下方。或者重命名可以随便根据自己的喜好设计,也可以不用重命名。

package com.project.util;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期工具类
 */
public class DateUtil {

	/**
	 * 日期对象转字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatDate(Date date,String format){
		String result="";
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		if(date!=null){
			result=sdf.format(date);
		}
		return result;
	}
	
	/**
	 * 字符串转日期对象
	 * @param str
	 * @param format
	 * @return
	 * @throws Exception
	 */
	public static Date formatString(String str,String format) throws Exception{
		if(StringUtil.isEmpty(str)){
			return null;
		}
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		return sdf.parse(str);
	}
	
	public static String getCurrentDateStr(){
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmssSSSSSSSSS");
		return sdf.format(date);
	}
	
	public static String getCurrentDatePath()throws Exception{
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
		return sdf.format(date);
	}
	
	public static void main(String[] args) {
		try {
			System.out.println(getCurrentDateStr());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

二、前端

在这里插入图片描述

<!-- 上传合同 -->
        <el-form-item label="上传合同" prop="cght">
          <el-upload
                  class="upload-demo"
                  :herders="headers"
                  :action="getServerUrl()+'asset/uploadContract'"
                  :limit="1"
                  :show-file-list="false"
                  :on-success="handleContractSuccess"
          >
            <el-row>
              <el-button type="primary">添加采购合同</el-button>
              <span style="font-size: 13px;color: #8d8d8d;margin-left: 15px">{{ fileName }}</span>
            </el-row>
          </el-upload>
        </el-form-item>

这里面:action中的getServerUrl()为自己封装的axios方法,表示http://localhost:8082/。可以直接写。

  1. 拼接url:getServerUrl()+‘asset/uploadContract’
  2. handleContractSuccess:自定义上传成功的方法

handleContractSuccess方法:

const fileName = ref("只允许上传PDF文件")
const handleContractSuccess = (res) => {
  fileName.value = res.data.title;
  form.value.cght = res.data.title;
}

上传成功时,右侧 “只允许上传PDF文件” 替换为文件名称,并且将文件名称传入定义的属性中,上传数据库。

三、演示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

可以看到文件上传成功,上传到指定位置并且重命名在表单成功显示

流程如上,前端完成!


结束

以上为全部内容,欢迎讨论,记录学习!

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
<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 BootVue的结合可使文件上传实现更加轻松快捷。 首先,需要在前端部分使用Vue来创建一个简单的文件上传组件,该组件可以实现文件选择、文件上传以及进度条的显示等功能。可以使用vue-file-upload或者其他类似的第三方库来实现文件上传功能,同时需要在该组件中设置上传API的路径和上传的文件名。 然后,需要在后端部分使用Spring Boot来处理上传的文件。Spring Boot提供了丰富的文件处理工具和API,可以轻松地实现文件上传。可以使用Spring Boot的MultipartResolver来解析文件上传请求,同时可以使用MultipartFile类来获取上传的文件对象。 接着,需要在Spring Boot的Controller中创建一个上传接口用于处理文件上传请求。该接口需要使用@RequestParam注解来获取上传的文件对象,并使用MultipartFile类来处理文件上传。同时,还需要设置上传文件的路径,并将上传成功后的文件路径返回到前端。 最后,需要在前端页面使用Vue来处理上传结果。根据上传返回的结果,可以在页面上显示上传成功或者上传失败的提示信息。同时,还可以使用Vue实现进度条的动态更新,用以提醒用户当前的上传状态。 总的来说,Spring BootVue的结合可以实现快速、高效的文件上传功能。借助两个框架提供的强大工具和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的文件上传组件,即可实现文件的上传功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值