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

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

  • 饿了么怎么改定位(饿了么怎么改定位城市)

    饿了么怎么改定位(饿了么怎么改定位城市)

  • 顺丰寄付现结怎么线上支付(顺丰寄付现结怎么改成寄付月结)

    顺丰寄付现结怎么线上支付(顺丰寄付现结怎么改成寄付月结)

  • 淘宝支持云闪付吗(淘宝支持云闪付商家也不能使用优惠券)

    淘宝支持云闪付吗(淘宝支持云闪付商家也不能使用优惠券)

  • 只知道微信昵称怎么找到对方(只知道微信昵称怎么查到微信号?)

    只知道微信昵称怎么找到对方(只知道微信昵称怎么查到微信号?)

  • 苹果x为什么更新不了软件(苹果x为什么更新不了系统)

    苹果x为什么更新不了软件(苹果x为什么更新不了系统)

  • 候补之后还能抢票吗(候补的时候还能抢票吗)

    候补之后还能抢票吗(候补的时候还能抢票吗)

  • 如何才能以100%的比例显示图像(如何才能以100%的比例显示头像)

    如何才能以100%的比例显示图像(如何才能以100%的比例显示头像)

  • 加装硬盘需要重装系统吗(加装硬盘需要重新装系统吗)

    加装硬盘需要重装系统吗(加装硬盘需要重新装系统吗)

  • qq群多少人满(qq群 多少人)

    qq群多少人满(qq群 多少人)

  • 滴滴派单不想接怎么办(滴滴派单不想接远单)

    滴滴派单不想接怎么办(滴滴派单不想接远单)

  • 佳能m50能拍星空吗(佳能m50能拍星空镜头吗)

    佳能m50能拍星空吗(佳能m50能拍星空镜头吗)

  • iphone镜像怎么关(怎么关苹果镜像)

    iphone镜像怎么关(怎么关苹果镜像)

  • oppo锁屏有广告怎么去掉(oppo锁屏广告怎么彻底关掉)

    oppo锁屏有广告怎么去掉(oppo锁屏广告怎么彻底关掉)

  • 13mp是多少像素(13mp是多少像素算大吗)

    13mp是多少像素(13mp是多少像素算大吗)

  • iphonexr怎么下载不了软件

    iphonexr怎么下载不了软件

  • 绑定pid是什么意思(绑定eip的作用)

    绑定pid是什么意思(绑定eip的作用)

  • 工作簿文件的扩展名(工作簿文件的扩展名为.xlsx)

    工作簿文件的扩展名(工作簿文件的扩展名为.xlsx)

  • 为什么前置和后置不一样(为什么前置和后置拍照差别那么大)

    为什么前置和后置不一样(为什么前置和后置拍照差别那么大)

  • 手机乘公交怎么扫码(手机乘公交怎么开发票)

    手机乘公交怎么扫码(手机乘公交怎么开发票)

  • 200m宽带用几类网线(200m宽带是)

    200m宽带用几类网线(200m宽带是)

  • 小米8se电池耐用吗(小米8se电池续航测试)

    小米8se电池耐用吗(小米8se电池续航测试)

  • vivox9水印相机怎么设置方法(vivox30水印相机)

    vivox9水印相机怎么设置方法(vivox30水印相机)

  • 钉钉如何去掉小目标提醒(钉钉如何去掉小窗口模式)

    钉钉如何去掉小目标提醒(钉钉如何去掉小窗口模式)

  • oppok3有耳机孔吗(oppok3能用typec接口耳机吗)

    oppok3有耳机孔吗(oppok3能用typec接口耳机吗)

  • 微信怎么关闭地区显示(微信怎么关闭地区显示2023)

    微信怎么关闭地区显示(微信怎么关闭地区显示2023)

  • 无法访问移动网络是怎么回事?手机无法访问移(无法访问移动网络怎么办)

    无法访问移动网络是怎么回事?手机无法访问移(无法访问移动网络怎么办)

  • 应交税费转出未交增值税借贷方表示什么
  • 这个季度报税时间怎么算
  • 劳务外包合同需要交税吗
  • 个税退税需要交税吗
  • 增值税延期滞纳金是多少
  • 公司装修费可以计入开办费吗
  • 去新成立的公司
  • 坏账准备的账务处理怎么理解
  • 红字发票是否要修改往期申报表
  • 借款到期一直付利息诉讼期怎么算
  • 增值税补交还有没有责任
  • 在文具公司工作怎么样
  • 异地工程预缴个税
  • 修理费要开税控清单吗
  • 税务行业软件
  • 银行结算卡年费多少
  • 政府补贴是否可享受即征即退优惠政策
  • 合并企业的增值税税率
  • 仓储费怎么账务处理
  • 有哪些凭证
  • 筹建期间的开办费包括哪些
  • 在windows7环境中鼠标主要的三种操作方式是
  • linux系统的文件与目录操作
  • 兼职人员工资如何扣税
  • 酒店采购布草如何入账
  • 委托加工物资企业原材料都是自己采购
  • 专项资金下达期限
  • 电脑麦克风没声音是什么原因
  • 公路客运车辆
  • 视频监控智能化应用
  • php执行脚本
  • php常见的错误级别
  • 广告代理费收取比例
  • cnn三层
  • emacs scheme
  • 应收利息的会计处理方法
  • 企业增值税的税收优惠有哪些
  • 打车费的会计分录
  • 帝国cms建站教程
  • 快递公司账务处理流程及方法总结
  • java中file的用法
  • 织梦官方网站
  • 购买项目用设备计入什么科目
  • 保证金存款账户需要销户吗
  • sqlserver数据库获取当前时间
  • sql server中字符串常量只能用双引号括起来
  • sql server必知必会
  • 注册资金只能增加不能减少吗
  • 社保局会给失业人员打电话吗
  • 购买花卉
  • 积分购物骗局
  • 实缴税额怎么算
  • 企业股东撤资如何清算
  • 坏账收回所得税需要确认收入吗汇算清缴表如何填报
  • 收到票据又转背书付了账务处理
  • 商品进销差价的作用
  • 税务局代开发票作废可以申请退税吗?
  • 法定盈余公积是什么
  • 企业预付账款的分录
  • 安装sql server 2008硬件要求
  • sql server的mdf文件怎么导入数据库
  • windows更新9%
  • windows update client
  • 如何保存xps文件
  • linux-gnu
  • win7系统防火墙无法关闭
  • win10怎么进去
  • win8.1拨号上网
  • Win10预览版拆弹
  • listview安卓
  • 猫的所有视频
  • flash和javascript
  • linux c语言获取当前路径
  • vue.js有什么用
  • unity data
  • python 脚本编写
  • android如何导入v4包
  • jquery操作元素样式
  • 销售货物免征增值税时收取的增值税税款需计入当期损益
  • 审计验资费计入什么科目
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设