位置: 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前端面试题最新)

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

  • android文件夹可以删除吗(android文件夹是干嘛的)

    android文件夹可以删除吗(android文件夹是干嘛的)

  • 华为最近删除里的照片删了还能恢复吗(华为最近删除里的照片怎么找回)

    华为最近删除里的照片删了还能恢复吗(华为最近删除里的照片怎么找回)

  • 苹果xr最佳充电方式(苹果xr最佳充电器)

    苹果xr最佳充电方式(苹果xr最佳充电器)

  • 微信怎么群聊视频通话(微信怎么群聊视频邀请)

    微信怎么群聊视频通话(微信怎么群聊视频邀请)

  • 怎么把视频设为来电铃声(怎么把视频设为铃声)

    怎么把视频设为来电铃声(怎么把视频设为铃声)

  • 商家查询次数是什么(商家查询次数是什么意思)

    商家查询次数是什么(商家查询次数是什么意思)

  • 新手机出现补丁日期正常吗(新手机出现补丁好吧)

    新手机出现补丁日期正常吗(新手机出现补丁好吧)

  • 华为售后贴膜免费吗(华为售后贴膜免费贴几年)

    华为售后贴膜免费吗(华为售后贴膜免费贴几年)

  • 华为文件管理在哪(华为文件管理在手机的哪里)

    华为文件管理在哪(华为文件管理在手机的哪里)

  • cpu configuration什么意思

    cpu configuration什么意思

  • 嘟的一声后正在通话中是什么意思(嘟的一声后正在通话中)

    嘟的一声后正在通话中是什么意思(嘟的一声后正在通话中)

  • 电脑怎么显示键盘(电脑怎么显示键盘灯)

    电脑怎么显示键盘(电脑怎么显示键盘灯)

  • oppoa59s相当于骁龙多少(oppoa59处理器相当骁龙)

    oppoa59s相当于骁龙多少(oppoa59处理器相当骁龙)

  • 拼多多买火车票怎么取票(拼多多买火车票可以先用后付吗)

    拼多多买火车票怎么取票(拼多多买火车票可以先用后付吗)

  • airpods三代上市时间(airpods三代上市价格)

    airpods三代上市时间(airpods三代上市价格)

  • 画图窗口是由几部分组成(画图窗口各部分名称)

    画图窗口是由几部分组成(画图窗口各部分名称)

  • 探探为什么下载不了啦(下载探探为什么还需要花钱)

    探探为什么下载不了啦(下载探探为什么还需要花钱)

  • 淘宝夜间模式怎么打开(淘宝夜间模式怎么没有了)

    淘宝夜间模式怎么打开(淘宝夜间模式怎么没有了)

  • 苹果xsmax支持nfc功能吗(苹果xsmax支持多少w充电)

    苹果xsmax支持nfc功能吗(苹果xsmax支持多少w充电)

  • nova4与nova4e的区别(nova4和nove4e对比)

    nova4与nova4e的区别(nova4和nove4e对比)

  • 国二选择题知识点(国二选择题题库)

    国二选择题知识点(国二选择题题库)

  • 荣耀v20有哪些解锁方式(荣耀v20是什么解锁)

    荣耀v20有哪些解锁方式(荣耀v20是什么解锁)

  • 苹果手机怎么把卡里电话导入手机(苹果手机怎么把通讯录导入手机卡)

    苹果手机怎么把卡里电话导入手机(苹果手机怎么把通讯录导入手机卡)

  • 爱奇艺弹幕怎么关闭(爱奇艺弹幕怎么设置一行)

    爱奇艺弹幕怎么关闭(爱奇艺弹幕怎么设置一行)

  • 惠普硒鼓怎么加粉(惠普硒鼓怎么加碳粉视频教程)

    惠普硒鼓怎么加粉(惠普硒鼓怎么加碳粉视频教程)

  • Vue3 + Element Plus 按需引入 - 自动导入(vue3elementplus首页布局)

    Vue3 + Element Plus 按需引入 - 自动导入(vue3elementplus首页布局)

  • 【Pytorch深度学习50篇】·······第六篇:【常见损失函数篇】-----BCELoss及其变种

    【Pytorch深度学习50篇】·······第六篇:【常见损失函数篇】-----BCELoss及其变种

  • Vue开发环境安装(vue开发环境配置)

    Vue开发环境安装(vue开发环境配置)

  • 税率的具体形式
  • 公司股东分红要交哪些税
  • 所得税汇算清缴账务处理
  • 销项负数发票能用吗
  • 工程类工资表为哪些内容
  • 股票发行的佣金计入什么科目
  • 残保金每次缴纳都是一样的吗
  • 出口货物退回需交税吗
  • 票据贴现的账务处理案例
  • 小规模纳税人汇算清缴要填什么表
  • 没有收到房租发票可以摊销吗?
  • 摊销租金是什么意思
  • 多计提以前年度损益调整账务处理怎么做
  • 高危职业人身意外险
  • 增值税专用发票抵扣期限
  • 企业多扣个税怎么处理
  • 免税农产品收入是否计入30万销售额
  • 运输发票的税率分类
  • 关于环保税的计税依据
  • 开票系统怎么改管理员名字
  • 所有利息收入都免税吗
  • 计提应付利息编制记账凭证用什么原始凭证?
  • 发票两边的孔怎么做
  • 企业所得税季度预缴可以弥补以前年度亏损吗
  • 预收贷款是什么会计科目
  • 咨询费如何缴纳个税
  • 建筑行业当月无收入成本如何结转?
  • linux系统怎么查看mac地址
  • 新会计准则下建筑业会计科目设置
  • 公司设备租赁给客户怎么做科目
  • 如何解决连接宽带的方法
  • win7系统咋样
  • 新准则管理费用税金
  • 公司给客户报销费用可以吗
  • 携税宝续费
  • 固定资产公允价值变动会计处理
  • php array_push()数组函数:将一个或多个单元压入数组的末尾(入栈)
  • 一般纳税人什么情况下可以开3%的税率
  • 报销员工餐费属于哪个科目
  • 矿产资源补偿费与采矿权价款区别
  • 简单实现php留言功能
  • springboot基本结构
  • 人工智能答案
  • thinkphp如何连接数据库
  • 物流辅助服务要办许可证吗
  • mysql 触发器
  • 辅助生产车间照明费用计入什么科目
  • 个体定额和不定额有什么区别
  • 独资企业和公司区别
  • 建筑企业开票都要交税吗
  • 出口企业出口退税流程
  • sqlserver阻止保存要求重新
  • ibm.data.db2
  • 固定资产未入账的定性依据
  • 工会经费税务代收是什么意思
  • 销售收入怎么入账
  • 总记账凭证核算怎么做
  • 支付设备款怎么做账
  • 协会会费怎么入账
  • 净现值率和现值指数与净现值什么时候它们评价结果一致
  • 会计凭证编制程序和用途
  • 研发费用人工费用包括
  • 如何用win7
  • mac闹钟app
  • osk.exe
  • ubuntu怎样调出命令行
  • linux r安装
  • 如何安装windowsxp
  • win7系统无法进入登录界面
  • Win7开机就蓝屏
  • win8.1系统电脑设置闪退
  • 微软强制升级
  • Win10双显卡怎么切换到独立显卡
  • win10无法打开wifi列表
  • shell中删除文件和目录
  • bat error
  • jquery常用操作
  • unity随机生成一个物体
  • 安置残疾人即征即退
  • 江西省国家税务局工作人员名单
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设