位置: IT常识 - 正文

SpringBoot+Vue实现文件上传下载功能

编辑:rootadmin
SpringBoot+Vue实现文件上传下载功能 前言

推荐整理分享SpringBoot+Vue实现文件上传下载功能,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

本文主要实现了以下功能: 1、 单文件上传以及多文件上传功能 2、 输入文件名下载文件功能 3、 输入音频文件名在线播放音频功能

一、项目基础部分搭建1.1 前端项目搭建1.1.1 新建前端项目

打开命令行输入以下命令,使用Vue CLI创建前端项目,Vue CLI安装教程

vue create file-demo

1.1.2 引入axios

输入以下命令在项目中引入axios

npm install axios --save

1.1.3 解决跨域问题

打开vue.config.js添加以下配置,修改启动端口,以及配置代理解决跨域问题

const { defineConfig } = require('@vue/cli-service')module.exports = defineConfig({ transpileDependencies: true})module.exports = { devServer: { // 修改前端项目启动端口号 port: 8081, proxy: { '^/file': { // 此处配置对应的后端端口 target: "http://localhost:8080", // 如果是https接口,需要配置这个参数为true secure: false, // 此处配置路径重写 pathRewrite: { '^/file': '/file' } } } }}1.2 后端项目搭建1.2.1 新建后端项目SpringBoot+Vue实现文件上传下载功能

打开IDEA,按照以下步骤创建一个新的SpringBoot项目

1.2.2 编辑配置文件

打开项目,编辑application.properties配置文件,输入以下配置

#可以选择性的修改或选择以下配置#配置服务端口server.port=8080#是否开启文件上传支持,默认是truespring.servlet.multipart.enabled=true#文件写入磁盘的阈值,默认是0spring.servlet.multipart.file-size-threshold=0#单个文件的最大值,默认是50MBspring.servlet.multipart.max-file-size=50MB#多个文件上传时的总大小 值,默认是100MBspring.servlet.multipart.max-request-size=100MB#是否延迟解析,默认是falsespring.servlet.multipart.resolve-lazily=false#自定义文件访问路径myfile.path=E:\\test\\dir二、文件上传功能2.1 单文件上传功能实现2.1.1 前端代码

在App.vue中添加如下代码,使用form标签实现文件上传功能

<template> <p>单文件上传</p> <form action="/file/uploadSingleFile" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="file"> <input type="submit"> </form></template>2.1.2 后端代码

在com.example.springbootdemo.controller包下创建UploadFileController.java文件

package com.example.springbootdemo.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;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;@Slf4j@RestController@RequestMapping("/file")public class UploadFileController { @Value("${myfile.path}") private String filePath; // 单文件上传功能 @PostMapping("/uploadSingleFile") public void uploadSingleFile(@RequestParam("file") MultipartFile multipartFile) { String fileName = multipartFile.getOriginalFilename(); File file = new File(filePath + '\\' + fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); log.info("父级文件目录不存在,已创建目录"); } try { multipartFile.transferTo(file); } catch (IOException e) { log.error("{}",e); log.error("程序错误,请重新上传"); e.printStackTrace(); } finally { log.info("文件上传成功,文件全路径名称为:{}",file.getPath()); } }}2.2 多文件上传功能实现2.2.1 前端代码

在App.vue中添加如下代码,使用form标签实现文件上传功能

<template> <p>多文件上传</p> <form action="/file/uploadMultipleFile" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="files" multiple="multiple"> <input type="submit"> </form></template>2.2.2 后端代码

在com.example.springbootdemo.controller包下创建UploadFileController.java文件

package com.example.springbootdemo.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;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;@Slf4j@RestController@RequestMapping("/file")public class UploadFileController { @Value("${myfile.path}") private String filePath; // 多文件上传功能实现 @PostMapping("/uploadMultipleFile") public void uploadMultipleFile(@RequestParam("files") MultipartFile multipartFiles[]) { for (MultipartFile multipartFile : multipartFiles) { String fileName = multipartFile.getOriginalFilename(); File file = new File(filePath + '\\' + fileName); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); log.info("父级文件目录不存在,已创建目录"); } try { multipartFile.transferTo(file); } catch (IOException e) { log.error("{}",e); log.error("程序错误,请重新上传"); e.printStackTrace(); } finally { log.info("文件上传成功,文件全路径名称为:{}",file.getPath()); } } }}三、文件下载功能3.1 普通文件下载功能实现3.1.1 前端代码

在App.vue中添加如下代码,使用form标签实现文件上传功能

<template> <p>文件下载{{inputData.fileName}}</p> <input type="text" placeholder="请输入全文件名" v-model="inputData.fileName"> <button @click="downloadFile">下载</button></template><script>import axios from 'axios';import { reactive } from 'vue';export default{ setup() { let inputData = reactive({ fileName:"" }) // 下载文件函数 async function downloadFile() { let BASE_URL = "/file"; let data = { ...inputData } console.log(inputData); await axios({ url: `${BASE_URL}/downloadFile`, method: "post" , data: data, headers: { 'Content-Type': 'application/json' }, responseType: 'blob', }).then((resp) => { const blob = new Blob([resp.data]); var downloadElement = document.createElement("a"); var href = window.URL.createObjectURL(blob); downloadElement.href = href; downloadElement.download = decodeURIComponent(inputData.fileName); document.body.appendChild(downloadElement); downloadElement.click(); document.body.removeChild(downloadElement); window.URL.revokeObjectURL(href); }); } return { inputData, downloadFile } }}</script>3.1.2 后端代码

在com.example.springbootdemo.controller包下建立DownloadFileController

package com.example.springbootdemo.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.Map;@Slf4j@RestController@RequestMapping("/file")public class DownloadFileController { @Value("${myfile.path}") private String filePath; @PostMapping("/downloadFile") public void downloadFile(@RequestBody Map<String, String> params, HttpServletRequest request, HttpServletResponse response) { log.info("文件名为:{}",params.get("fileName")); if (!params.containsKey("fileName") || params.get("fileName") == null || "".equals(params.get("fileName"))) { log.info("文件名不存在"); return; } if (filePath == null || "".equals(filePath)) { log.info("文件路径不存在"); return; } String fileName = params.get("fileName"); String fullPath = filePath + "\\" + fileName; try { download(request,response, fullPath, fileName); } catch (Exception e) { log.error("{}",e); log.error("文件下载失败"); e.printStackTrace(); } } // 下载文件方法: public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String realName) throws Exception { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long fileLength = (new File(filePath)).length(); response.setContentType("application/octet-stream;charset=GBK"); response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("GB2312"), "ISO-8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } bis.close(); bos.close(); }}3.2 音频文件在线播放功能实现3.2.1 前端代码

在App.vue中添加如下代码,使用form标签实现文件上传功能

<template> <p>文件下载{{inputData.fileName}}</p> <input type="text" placeholder="请输入全文件名" v-model="inputData.fileName"> <button @click="downloadFile">下载</button> <p>音乐在线播放{{}}</p> <input type="text" placeholder="请输入音乐文件名" v-model="inputData.fileName"> <button @click="playMusic">播放音乐</button> <br> <audio controls currentTime autoplay :src='audioSrc.data'></audio></template><script>import axios from 'axios';import { reactive } from 'vue';export default{ setup() { let inputData = reactive({ fileName:"" }) let audioSrc = reactive({ data:"" }); // 在线播放音乐函数 async function playMusic() { let BASE_URL = "/file"; let data = { ...inputData } console.log(inputData); await axios({ url: `${BASE_URL}/downloadFile`, method: "post" , data: data, headers: { 'Content-Type': 'application/json' }, responseType: 'blob', }).then((Blobdata) => { audioSrc.data = window.URL.createObjectURL(Blobdata.data); }); } return { inputData, audioSrc, playMusic } }}</script>3.2.2 后端代码

在com.example.springbootdemo.controller包下建立DownloadFileController

package com.example.springbootdemo.controller;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.util.Map;@Slf4j@RestController@RequestMapping("/file")public class DownloadFileController { @Value("${myfile.path}") private String filePath; @PostMapping("/downloadFile") public void downloadFile(@RequestBody Map<String, String> params, HttpServletRequest request, HttpServletResponse response) { log.info("文件名为:{}",params.get("fileName")); if (!params.containsKey("fileName") || params.get("fileName") == null || "".equals(params.get("fileName"))) { log.info("文件名不存在"); return; } if (filePath == null || "".equals(filePath)) { log.info("文件路径不存在"); return; } String fileName = params.get("fileName"); String fullPath = filePath + "\\" + fileName; try { download(request,response, fullPath, fileName); } catch (Exception e) { log.error("{}",e); log.error("文件下载失败"); e.printStackTrace(); } } // 下载文件方法: public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String realName) throws Exception { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long fileLength = (new File(filePath)).length(); response.setContentType("application/octet-stream;charset=GBK"); response.setHeader("Content-disposition", "attachment; filename=" + new String(realName.getBytes("GB2312"), "ISO-8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } bis.close(); bos.close(); }}
本文链接地址:https://www.jiuchutong.com/zhishi/295681.html 转载请保留说明!

上一篇:web前端面试高频考点——Vue的高级特性(动态组件、异步加载、keep-alive、mixin、Vuex、Vue-Router)(web前端面试题最新)

下一篇:前端是什么,是干嘛的(前端是指什么工作)

  • 西门子智能照明系统培训(西门子智能照明系统)(西门子智能照明控制模块使用说明)

    西门子智能照明系统培训(西门子智能照明系统)(西门子智能照明控制模块使用说明)

  • 华为手机备忘录怎么设置密码(华为手机备忘录提醒铃声设置)

    华为手机备忘录怎么设置密码(华为手机备忘录提醒铃声设置)

  • 淘宝退货单号在哪里看(得物申请退货流程)

    淘宝退货单号在哪里看(得物申请退货流程)

  • 华为p20隐藏图标(华为p20隐藏图标怎么恢复)

    华为p20隐藏图标(华为p20隐藏图标怎么恢复)

  • ip地址错误网络无法接通win10(ip地址错误网络无法连接win7)

    ip地址错误网络无法接通win10(ip地址错误网络无法连接win7)

  • 如何判断soul限流(soul怎么看出自己是否被屏蔽)

    如何判断soul限流(soul怎么看出自己是否被屏蔽)

  • 腾讯课堂自己可以看时长吗(腾讯课堂可以直接进入吗)

    腾讯课堂自己可以看时长吗(腾讯课堂可以直接进入吗)

  • 数据库系统的三级模式不包括(数据库系统的三个主要部分)

    数据库系统的三级模式不包括(数据库系统的三个主要部分)

  • iphoneid可以两个手机一起用吗(苹果id可以两个人用一个吗)

    iphoneid可以两个手机一起用吗(苹果id可以两个人用一个吗)

  • 淘宝不评价多久会自动消(淘宝不评价多久自动评价)

    淘宝不评价多久会自动消(淘宝不评价多久自动评价)

  • 磊科路由器恢复出厂后没网了(磊科路由器恢复出厂设置后怎么重新设置)

    磊科路由器恢复出厂后没网了(磊科路由器恢复出厂设置后怎么重新设置)

  • 像素多少算高清(相机4800万像素算高吗)

    像素多少算高清(相机4800万像素算高吗)

  • b站粉丝牌子怎么获得(b站 粉丝牌)

    b站粉丝牌子怎么获得(b站 粉丝牌)

  • word文档怎么添加页面(word文档怎么添加方框)

    word文档怎么添加页面(word文档怎么添加方框)

  • 华为账号为什么要实名认证(华为账号为什么是别人的身份证)

    华为账号为什么要实名认证(华为账号为什么是别人的身份证)

  • 华为蓝牙耳机freebud3使用方法(华为蓝牙耳机freelace)

    华为蓝牙耳机freebud3使用方法(华为蓝牙耳机freelace)

  • iPhone11pro有几种机身颜色(苹果11pro有几款)

    iPhone11pro有几种机身颜色(苹果11pro有几款)

  • 苹果表可以单独使用吗(苹果表单独用听歌)

    苹果表可以单独使用吗(苹果表单独用听歌)

  • 华为mate20录音功能在哪(华为mate20录音机在哪)

    华为mate20录音功能在哪(华为mate20录音机在哪)

  • 微信发定位在哪里设置(微信发定位在哪设置精准位置信息)

    微信发定位在哪里设置(微信发定位在哪设置精准位置信息)

  • 苹果播客是什么(iphone的播客是什么)

    苹果播客是什么(iphone的播客是什么)

  • vivox27支持面部解锁吗(vivox27支持脸部解锁吗)

    vivox27支持面部解锁吗(vivox27支持脸部解锁吗)

  • 如何获取OPPO手机的root权限(如何获取oppo手机密码)

    如何获取OPPO手机的root权限(如何获取oppo手机密码)

  • 淘票票如何使用兑换码(淘票票怎么使用)

    淘票票如何使用兑换码(淘票票怎么使用)

  • 华为p10安全模式怎么解除(华为p10plus安全模式)

    华为p10安全模式怎么解除(华为p10plus安全模式)

  • js执行上下文的类型(js执行上下文的概念)

    js执行上下文的类型(js执行上下文的概念)

  • 三税率什么意思
  • 价内税有哪些税种
  • 处置固定资产亏了怎么做账
  • 农业合作社享受优惠政策
  • 冲销以前年度营业外支出
  • 提供教育服务免征增值税文件
  • 增值税发票信息错误可以作废重开吗
  • 个人所得税已申报税额合计是什么意思
  • 房地产开发企业会计科目
  • 小规模购买财务软件怎么做分录
  • 资产收购账务处理
  • 坏账准备金最新计算公式
  • 劳务和工资合并扣税吗
  • 城镇土地使用税的计税依据
  • 经营方式变更说明
  • 冲回坏账准备是什么意思
  • 成本核算的一般步骤
  • win11安卓子系统在哪打开
  • 投资性房地产出售
  • vue onshow
  • 公司赞助是什么意思
  • vue中的...
  • 我找到了这个
  • 云霞下的麦田
  • 存货包括其他业务成本吗
  • 自建办公楼装修要报建吗
  • 提租补贴计入个税吗
  • 对于企业无法支付的应付账款
  • javafiles
  • Es6的新特性promise对象的设计初衷是
  • Vite4+Pinia2+vue-router4+ElmentPlus搭建Vue3项目(组件、图标等按需引入)[保姆级]
  • python怎么求列表里的和
  • 理财产品利息计算方法
  • 公允价值怎么记账
  • 大华摄像头海康威视录像机
  • phpcms安装
  • 织梦cms要钱吗
  • 支付宝支付凭证在哪里查
  • 个人社保的缴纳时间
  • 采购成本和销售成本谁影响利润
  • 小规模纳税人结转增值税的账务处理
  • 公司支付款项制度
  • 固定资产是怎么算出来的
  • 金税四期视频
  • 什么叫金税四期呢?
  • 固定资产办理竣工结算之后的处理方式
  • 电子税务局没有增值税申报怎么办?
  • 团体意外险投保
  • 合伙企业分配利润法律依据
  • 建筑施工仪器设备有哪些
  • 接受劳务应付未付款费用
  • 坏账损失的定义
  • 持有至到期投资减值准备可以转回吗
  • 私营公司待摊费怎么算
  • 企业注销怎么回事
  • mysql的基本操作语句
  • windows任务管理
  • ubuntu18.04更新到20.04
  • centos8安装锐速
  • 文件属性命令
  • 修改win7
  • mac安装nodejs的权限问题
  • android中常用的adapter不包括
  • unity游戏之友利拟收购《刀塔传奇》发行商中清龙图
  • 脚本控制三行三列怎么写
  • python 编程技巧
  • python数据验证
  • 支付宝是怎么写
  • scrapy—redis
  • 获取某个div的高度
  • JavaScript中的变量名不区分大小写
  • unity3d 场景
  • ubuntu没有xauthority
  • jquery日期选择器
  • 河南电子税务局官网app
  • 云南发票网站
  • 动车票电子发票如何获取
  • 税务部门组织收入会议报道
  • 纳税人不办税务许可证
  • 广西国税电话号码
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设