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

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

  • word艺术字环绕方式怎么设置(word艺术字环绕方式紧密型)

    word艺术字环绕方式怎么设置(word艺术字环绕方式紧密型)

  • 抖音我关注的人怎么没有了(抖音我关注的人不让别人看到)

    抖音我关注的人怎么没有了(抖音我关注的人不让别人看到)

  • 积目显示有消息点开没有了(积目显示有消息打开却没有)

    积目显示有消息点开没有了(积目显示有消息打开却没有)

  • ipadair3容易弯吗(ipad air3容易变弯吗)

    ipadair3容易弯吗(ipad air3容易变弯吗)

  • word左右分页变成上下分页怎么弄(word左右分页变成上下分页联想小新)

    word左右分页变成上下分页怎么弄(word左右分页变成上下分页联想小新)

  • 小米手机开视频不能开手电筒(小米手机开视频声音小,怎么办?)

    小米手机开视频不能开手电筒(小米手机开视频声音小,怎么办?)

  • lxe文件用什么软件打开(lx文件用什么打开)

    lxe文件用什么软件打开(lx文件用什么打开)

  • 华为nova5z和5ipro区别(华为nova5z和5ipro啥区别)

    华为nova5z和5ipro区别(华为nova5z和5ipro啥区别)

  • 抖音注销了显示什么(抖音注销了显示用手机号码登录)

    抖音注销了显示什么(抖音注销了显示用手机号码登录)

  • vivo手机如何快速充满电(vivo手机如何快速打开手电筒)

    vivo手机如何快速充满电(vivo手机如何快速打开手电筒)

  • 抖音已超出关注上限怎么办(抖音已超出关注怎么删除)

    抖音已超出关注上限怎么办(抖音已超出关注怎么删除)

  • 512kbps是多少网速(512kbps等于多少m)

    512kbps是多少网速(512kbps等于多少m)

  • 怎么定位苹果耳机盒子(怎么定位苹果耳机充电仓)

    怎么定位苹果耳机盒子(怎么定位苹果耳机充电仓)

  • 常用镜头可分为哪两种(常用镜头可分为哪几类)

    常用镜头可分为哪两种(常用镜头可分为哪几类)

  • 荣耀20和20s的区别(荣耀20和20S的区别)

    荣耀20和20s的区别(荣耀20和20S的区别)

  • 京东怎么跟客服发视频(京东怎么跟客服发图片)

    京东怎么跟客服发视频(京东怎么跟客服发图片)

  • 全民k歌怎么录歌(全民k歌怎么录屏唱歌有声音的那种)

    全民k歌怎么录歌(全民k歌怎么录屏唱歌有声音的那种)

  • 2016111是什么型号呢(20161117是什么星座)

    2016111是什么型号呢(20161117是什么星座)

  • wps触发器怎么设置(wps触发器怎么使用)

    wps触发器怎么设置(wps触发器怎么使用)

  • 三星s6打不进电话怎么回事(三星s6冲不进去电怎么办)

    三星s6打不进电话怎么回事(三星s6冲不进去电怎么办)

  • 滴滴出行预付款会退吗(滴滴出行预付款多久退)

    滴滴出行预付款会退吗(滴滴出行预付款多久退)

  • 视频动态怎么发(视频动态怎么发长视频)

    视频动态怎么发(视频动态怎么发长视频)

  • vivox9s怎么恢复系统还原(vivox9s怎么恢复出厂设置视频)

    vivox9s怎么恢复系统还原(vivox9s怎么恢复出厂设置视频)

  • 华为穿戴和华为运动健康有什么区别(华为穿戴和华为健康)

    华为穿戴和华为运动健康有什么区别(华为穿戴和华为健康)

  • 笔记本电池鼓包(笔记本电池鼓包了还能用吗)

    笔记本电池鼓包(笔记本电池鼓包了还能用吗)

  • 划转国有划拨土地要交契税吗?
  • 怎么做税种
  • 初税亩是什么意思
  • 2023年增值税税率表
  • 转出未交增值税是借方还是贷方
  • 我国会计准则规定,会计核算以人民币为记账本位币
  • 收到所得税退税会计怎么记账
  • 报销销售部门差旅费
  • 购置房屋
  • 车船税滞纳
  • 企业总资产是否包含累积折旧
  • 汽车修理店业务范围
  • 天然气安装工程施工劳务协议
  • 增值税应交税费科目
  • 固定资产入账必须有发票吗
  • 出口用的增值税税率
  • 银行贷款的纳税申报表指的所得税还是增值税
  • 稿酬所得个人所得税税率
  • 增值税发票查验平台显示查无此票
  • 递延所得税怎么计提
  • 收到退印花税款怎么入账
  • 会计估计变更由谁审批
  • 货物退回发票冲红会计分录
  • 实验耗材发票内容怎么写
  • 暂估金额与发票金额的区别
  • 主营业务收入需要交增值税吗
  • 公司经营权补偿款会计处理?
  • 分公司使用总公司业绩投标
  • 积分全部换购商品是什么
  • windows7公用网络
  • 美元汇款怎么汇
  • 资产负债表期初和期末指的是什么
  • 不予抵扣的进项税额是什么意思
  • 不征税收入与免税收入的区别
  • wmpdmc.exe是什么意思
  • nomoreporn.exe - nomoreporn是什么进程 有什么用
  • 补缴社保会被税务稽查吗
  • 房屋修理费用
  • 购买加油卡能否抵扣
  • vue引入高德地图绘制多边形,编辑多边形
  • 建筑业营改增后税务问题
  • 基于vue的网上商城
  • 收到社保稳岗补贴转入营业外收入要交企业所得税吧
  • node最新版本
  • css水平居中和垂直居中怎么设置
  • 不良品扣款应入哪个科目
  • 关于实收资本的表述中,不正确的是
  • 现金流量表的填列方法
  • 公司缴纳社保如何做账
  • 欠对方钱对方公司已注销
  • 游戏公司不开票怎么缴税
  • 费用报销单怎么填写
  • 递延所得税资产和所得税费用的关系
  • 车间设备折旧费计入产品成本吗
  • 交易性金融资产的入账价值
  • 小规模购进商品怎么做账
  • 软件企业技术开发增值税税率
  • 建筑施工企业检查的内容包括什么
  • 进项税额可以抵扣会计分录
  • 暂估固定资产的账务处理
  • 旅游业开具的是什么证明
  • 总资产报酬率的公式
  • 红字发票是怎么开的
  • 其他业务收入在资产负债表哪里体现
  • 固定资产明细账范本
  • 数据表的联接
  • sql有没有返回上一步
  • 组策略怎么用
  • 怎么设置pe系统
  • windows7磁盘清理命令
  • ExtJS4给Combobox设置列表中的默认值示例
  • jquery 选择
  • nodejs自启动
  • Python爬取qq music中的音乐url及批量下载
  • jquery 回车
  • django pypy
  • js的变量
  • 安卓自定义app
  • 关联企业业务往来税收调整
  • 上海自贸试验区临港新片区
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设