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

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

  • 新浪微博活动需知注意事项(微博搞活动是真的吗)

    新浪微博活动需知注意事项(微博搞活动是真的吗)

  • 苹果电脑摄像头怎么打开(苹果电脑摄像头怎么开启权限设置)

    苹果电脑摄像头怎么打开(苹果电脑摄像头怎么开启权限设置)

  • iphone13怎么戴口罩解锁(iPhone13怎么戴口罩人脸识别)

    iphone13怎么戴口罩解锁(iPhone13怎么戴口罩人脸识别)

  • 爱奇艺账号在哪里看(爱奇艺账号在哪里登录)

    爱奇艺账号在哪里看(爱奇艺账号在哪里登录)

  • 戴尔g3一键强冷哪个键(戴尔g3强冷模式)

    戴尔g3一键强冷哪个键(戴尔g3强冷模式)

  • qq会员可以隐藏吗(qq会员可以隐藏点赞吗)

    qq会员可以隐藏吗(qq会员可以隐藏点赞吗)

  • 手机管家有必要装吗(手机管家有必要下载吗)

    手机管家有必要装吗(手机管家有必要下载吗)

  • 历史下载记录在哪(以前下载记录)

    历史下载记录在哪(以前下载记录)

  • 小红书发布笔记被显示违规有什么影响(小红书发布笔记技巧)

    小红书发布笔记被显示违规有什么影响(小红书发布笔记技巧)

  • 手机关机打电话开机后会显示吗(手机关机打电话会有记录吗)

    手机关机打电话开机后会显示吗(手机关机打电话会有记录吗)

  • 抖音怎么一键删除无效视频(抖音怎么一键删除所有聊天记录)

    抖音怎么一键删除无效视频(抖音怎么一键删除所有聊天记录)

  • oppo老是自动静音(oppo手机怎么会自动静音)

    oppo老是自动静音(oppo手机怎么会自动静音)

  • 手机lens什么意思(手机leioa是什么牌子)

    手机lens什么意思(手机leioa是什么牌子)

  • 电脑微信怎么静音(电脑微信静音怎么设置)

    电脑微信怎么静音(电脑微信静音怎么设置)

  • 淘气值多少可以极速退款(淘气值多少可以助力喵币)

    淘气值多少可以极速退款(淘气值多少可以助力喵币)

  • 送话器自己能修复吗(送话器好修吗)

    送话器自己能修复吗(送话器好修吗)

  • 华为nova5怎么更换唤醒词(华为nova5怎么更换锁屏壁纸)

    华为nova5怎么更换唤醒词(华为nova5怎么更换锁屏壁纸)

  • 如何关闭来电闪光灯(如何关闭来电闪光灯华为)

    如何关闭来电闪光灯(如何关闭来电闪光灯华为)

  • 中央处理器由什么组成(中央处理器由什么单元组成)

    中央处理器由什么组成(中央处理器由什么单元组成)

  • id软件的全称是什么(id软件介绍)

    id软件的全称是什么(id软件介绍)

  • 京东评价不能删除吗(京东评价能不能删掉)

    京东评价不能删除吗(京东评价能不能删掉)

  • 换手机屏幕怎么知道是否原装(换手机屏幕怎么涂胶)

    换手机屏幕怎么知道是否原装(换手机屏幕怎么涂胶)

  • iphonex有广角镜头吗(iphone x广角镜头)

    iphonex有广角镜头吗(iphone x广角镜头)

  • iphonex放大镜关不掉了(iphone x 关闭放大镜)

    iphonex放大镜关不掉了(iphone x 关闭放大镜)

  • qq被限制加好友怎么办(qq被限制加好友是什么意思)

    qq被限制加好友怎么办(qq被限制加好友是什么意思)

  • 为什么电脑开机要按F1?(为什么电脑开机显示无信号然后黑屏)

    为什么电脑开机要按F1?(为什么电脑开机显示无信号然后黑屏)

  • imontray.exe是不是病毒 是什么进程 imontray进程有什么用(mom.exe是什么)

    imontray.exe是不是病毒 是什么进程 imontray进程有什么用(mom.exe是什么)

  • 如何在vue中实现文件预览功能(vue实战技巧)

    如何在vue中实现文件预览功能(vue实战技巧)

  • Python数学建模三剑客之Matplotlib(数学建模python 怎么用)

    Python数学建模三剑客之Matplotlib(数学建模python 怎么用)

  • 跨区域涉税事项报验是什么意思
  • 企业所得税减免所得税额计算公式
  • 税务硕士是什么学位类别
  • 增值税减免税申报明细表免税代码和名称
  • 什么企业可以开增值税专用发票
  • 自建厂房出售如何计算所得税
  • 计提应付票据利息的会计分录
  • 可抵扣的固定资产
  • 公司开办期间的费用如何处理
  • 加油站固定资产折旧年限
  • 银行收回贷款本息企业怎么做分录
  • 抬头是别的公司怎么报销
  • 开具发票财务需要管理吗?
  • 装修发票是什么发票
  • 关联企业纳税调整期限
  • 微信提现收取手续费多少钱
  • 公司注销要交分红税吗
  • 知识产权 申请
  • win10更新21h1后很卡
  • 收到税费返还是什么现金流量
  • php23种设计模式
  • deepin声音
  • 股权转让的不仅是权利还有义务
  • mtask.exe - mtask是什么进程 有什么用
  • 药品生产企业应建立
  • 在校学生是不是纳税人,请举例说明
  • 财务比率分析的主要内容
  • 简易办法征收增值税政策的通知
  • 150讲轻松搞定python网络爬虫
  • js生成随机数字和字母组合
  • 车险开的发票里有代收车船税吗
  • 融资租入固定资产
  • bug的定位和跟踪
  • 审图费谁出
  • 现金股利算负债吗
  • 银行承兑汇票贴现分录
  • 免税收入和免征
  • 印花税没有及时交会有什么后果
  • 季度利润是负数怎么办
  • 国有土地租赁合同的性质
  • 年会服装费属于什么费用
  • 固定资产的货币时间价值
  • 物业公司物业费税率是多少
  • 房产税是按不含增值税计提吗
  • 发出商品的增值税
  • 库存暂估入账的会计分录
  • 个人对企事业单位的看法
  • 营业外支出在贷方
  • 汽车装修费计入哪个科目
  • 政府会计制度之1613在建工程
  • 企业对外借款是什么意思
  • 支票小写金额可以涂改吗
  • 企业取得土地使用权会计处理
  • 财务控制的方法和措施
  • sql必学必会
  • 安装好sql2000后安装sp4
  • Win7系统进入桌面后点每个文件都会打转
  • 光盘安装系统怎么操作
  • macbook key
  • wind8桌面
  • Win10装不上是什么原因
  • win10预览版bug
  • linux主要充当什么样的服务角色
  • win10一年更新几次
  • win8系统多少位
  • win8系统怎么设置
  • win8系统电脑卡
  • cocos2d开发app
  • 安装centos no such device
  • js的isnan
  • android使用so
  • 汉诺塔游戏教程
  • node cd
  • androidui框架
  • js == ===区别
  • java script教程
  • javascript面向对象精要pdf
  • js遍历foreach
  • 深圳税务局怎么添加办税员
  • 出版社税费多少
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设