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

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

  • 怎样提升微博话题的关注度(如何提升一个微博账号的影响力和话语权)

    怎样提升微博话题的关注度(如何提升一个微博账号的影响力和话语权)

  • wps怎么去水印(wps怎么去水印文字)

    wps怎么去水印(wps怎么去水印文字)

  • opporeno4怎么关机(opporeno4怎么关机开机)

    opporeno4怎么关机(opporeno4怎么关机开机)

  • 怎么判断微信是大号还是小号(怎么判断微信是否被盗号)

    怎么判断微信是大号还是小号(怎么判断微信是否被盗号)

  • 三星手机黑屏怎么恢复(三星手机黑屏怎么导出数据)

    三星手机黑屏怎么恢复(三星手机黑屏怎么导出数据)

  • 比心线下接单的规则(比心有接线下单的吗)

    比心线下接单的规则(比心有接线下单的吗)

  • 手机的nfc功能是啥意思(手机的nfc功能是自带的吗)

    手机的nfc功能是啥意思(手机的nfc功能是自带的吗)

  • 抖音被别人屏蔽是什么状态(抖音被别人屏蔽还可以搜到吗)

    抖音被别人屏蔽是什么状态(抖音被别人屏蔽还可以搜到吗)

  • se2多大屏幕尺寸(苹果se2多少寸屏幕尺寸)

    se2多大屏幕尺寸(苹果se2多少寸屏幕尺寸)

  • 抖音审核通过了为什么别人看不到(抖音审核通过了播放量不增加)

    抖音审核通过了为什么别人看不到(抖音审核通过了播放量不增加)

  • 小米插座wifi版连不上(小米插座wifi版连接不上)

    小米插座wifi版连不上(小米插座wifi版连接不上)

  • 字数和字符数的区别(字符数与字数相差很大怎么办)

    字数和字符数的区别(字符数与字数相差很大怎么办)

  • 小米9微信视频怎么美颜(小米9微信视频美颜功能怎么开)

    小米9微信视频怎么美颜(小米9微信视频美颜功能怎么开)

  • oppo reno z屏幕分辨率(oppo reno z怎么分屏)

    oppo reno z屏幕分辨率(oppo reno z怎么分屏)

  • 抖音怎么加长腿特效(抖音怎么长腿打开)

    抖音怎么加长腿特效(抖音怎么长腿打开)

  • 淘宝盖楼是什么意思(淘宝盖楼有什么用)

    淘宝盖楼是什么意思(淘宝盖楼有什么用)

  • 苹果11后面是什么材质(苹果11后面是什么系列)

    苹果11后面是什么材质(苹果11后面是什么系列)

  • 苹果x多少万像素(苹果x像素多少万像素)

    苹果x多少万像素(苹果x像素多少万像素)

  • qq坦白局是匿名提问吗(qq坦白说匿名吗)

    qq坦白局是匿名提问吗(qq坦白说匿名吗)

  • opsson是什么牌子手机(opsson是什么牌子手机多少钱)

    opsson是什么牌子手机(opsson是什么牌子手机多少钱)

  • 怎么登录别人爱奇艺会员(陌陌怎么登录不了)

    怎么登录别人爱奇艺会员(陌陌怎么登录不了)

  • 触宝如何自己安装(触宝如何自己安装图片)

    触宝如何自己安装(触宝如何自己安装图片)

  • vue中如何使用vue-pdf及相应报错解决(vue中如何使用weboffice)

    vue中如何使用vue-pdf及相应报错解决(vue中如何使用weboffice)

  • Win11如何安装打印机?Win11安装共享打印机的方法介绍(win 11怎么安装)

    Win11如何安装打印机?Win11安装共享打印机的方法介绍(win 11怎么安装)

  • Linux下的web服务器搭建(linux中web服务器的安装,配置与测试)

    Linux下的web服务器搭建(linux中web服务器的安装,配置与测试)

  • python TKinter弹出式菜单的使用(python tkinter ttk)

    python TKinter弹出式菜单的使用(python tkinter ttk)

  • 律师事务所个人所得税如何计算
  • 旅游业成本具体有哪些
  • 组成计税价格公式消费税
  • 存货的期末余额在借方还是贷方
  • 未入账的固定资产处理的财务处理
  • 销项税最后转到哪里
  • 无偿使用房屋
  • 公司从个人手中租房不能取得发票
  • 打桩和挖土
  • 企业之间现金换承兑合法吗
  • 员工迟到扣款该怎么处理
  • 没有计提坏账准备的应收帐款坏帐帐务处理
  • 营改增后印花税计税依据文件
  • 公司收生育津贴怎么入账
  • 企业账户短信提醒可以用别人手机号吗
  • 购进材料再销售怎么会计分录
  • 帮客户采购会计分录
  • 计提附加税的会计分录怎么写
  • 采用视同买断方式代销商品怎么记账?
  • 其他货币资金明细科目有哪些
  • 商业写字楼
  • win10怎么清空
  • 维修机器设备买什么好
  • 施工企业内部往来核算方法包括( )
  • 酒水专用发票税率
  • 公司固定资产出售给个人
  • 工资税后补扣是什么意思
  • php数组函数有哪些
  • php 7z
  • php的!
  • cmt.exe病毒
  • 经济业务原始凭证分录
  • php去除空格和换行符
  • PHP:mcrypt_enc_is_block_algorithm()的用法_Mcrypt函数
  • 企业盈利结转本年利润分录
  • 企业持有待售的固定资产,应当对其预计
  • web前端视频教程全套
  • Deep Learning Tuning Playbook(深度学习调参手册中译版)
  • userpasswords
  • 原始凭证必要时可以涂改
  • mysql 长事务
  • 汇算清缴的所得税怎么做账
  • 利润表没有本月金额只有本年累计可以吗
  • mongodb如何修改数据
  • 营业收入比销售商品收到的现金大
  • 土地增值税预缴计税依据
  • 普通发票上的银行账户有规定吗
  • 销售商品该如何改进服务
  • 增值税期末有留抵税额应该怎么结转
  • 工程机械租赁公司注册
  • 商场扣点怎么做分录
  • 应交增值税进项税额转出账务处理
  • 贸易公司的会计要做哪些报表
  • 无发票费用可以入账吗
  • 长期股权投资两种核算方法的区别
  • 党费结余如何计算
  • 固定资产发票未到可以确认固定资产吗
  • 个人独资企业要报税吗
  • windows使用痕迹是指是什么
  • MySQL数据库中把表中的一个字段重命名
  • mysql获取当前行数
  • grub2引导win10
  • windows update client
  • 微软安全信息如何替换
  • windows设置tomcat自动重启
  • windows的安装方式有哪些
  • winxp软件双击后没有反应
  • lnmp一键安装包是什么
  • 极限竞速中心应用程序
  • win7自动更新失败怎么删除更新启动
  • jquery实现回到顶部
  • 有道词典手机
  • unable to instantiate default
  • python 3.5下xadmin的使用及修复源码bug
  • javascript中的函数该如何理解
  • 适用于分析原因的工具有哪些
  • python连接mq
  • javascript中继承
  • 鉴证服务是指什么
  • 江西公积金提取代办
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设