vue上传大文件/视频前后端(java)代码

  • 一、上传组件
  • 二、后端java代码
  • 注意:

一、上传组件

<template><div><!-- 上传组件 --><el-upload action drag :auto-upload="false" :show-file-list="false" :on-change="handleChange"><i class="el-icon-upload"></i><div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div><div class="el-upload__tip" slot="tip">大小不超过 200M 的视频</div></el-upload><!-- 进度显示 --><div class="progress-box"><span>上传进度:{{ percent.toFixed() }}%</span><el-button type="primary" size="mini" @click="handleClickBtn">{{ upload | btnTextFilter}}</el-button></div></div>
</template><script>import { getUUID } from '@/utils'import axios from 'axios'export default {name: 'singleUpload',props: {value: String},filters: {btnTextFilter(val) {return val ? '暂停' : '继续'}},data() {return {videoUrl: this.value,percent: 0,upload: true,percentCount: 0,suffix: '',fileName: '',preName: ''}},methods: {emitInput(val) {this.$emit('input', val)},async handleChange(file) {if (!file) returnthis.percent = 0this.percentCount = 0// 获取文件并转成 ArrayBuffer 对象const fileObj = file.rawlet buffertry {buffer = await this.fileToBuffer(fileObj)} catch (e) {console.log(e)}// 将文件按固定大小(2M)进行切片,注意此处同时声明了多个常量const chunkSize = 2097152,chunkList = [], // 保存所有切片的数组chunkListLength = Math.ceil(fileObj.size / chunkSize), // 计算总共多个切片suffix = /\.([0-9A-z]+)$/.exec(fileObj.name)[1] // 文件后缀名this.preName = getUUID() //生成文件名前缀this.fileName = this.preName+'.'+suffix //文件名 // 生成切片,这里后端要求传递的参数为字节数据块(chunk)和每个数据块的文件名(fileName)let curChunk = 0 // 切片时的初始位置for (let i = 0; i < chunkListLength; i++) {const item = {chunk: fileObj.slice(curChunk, curChunk + chunkSize),fileName: `${this.preName}_${i}.${suffix}` // 文件名规则按照 filename_1.jpg 命名}curChunk += chunkSizechunkList.push(item)}this.chunkList = chunkList // sendRequest 要用到this.sendRequest()},// 发送请求sendRequest() {const requestList = [] // 请求集合this.chunkList.forEach((item, index) => {const fn = () => {const formData = new FormData()formData.append('chunk', item.chunk)formData.append('filename', item.fileName)return axios({url: 'http://localhost/api/chunk',method: 'post',headers: { 'Content-Type': 'multipart/form-data' },data: formData}).then(response => {if (response.data.errcode === 0) { // 成功if (this.percentCount === 0) { // 避免上传成功后会删除切片改变 chunkList 的长度影响到 percentCount 的值this.percentCount = 100 / this.chunkList.length}if (this.percent >= 100) {this.percent = 100;}else {this.percent += this.percentCount // 改变进度}if (this.percent >= 100) {this.percent = 100;}this.chunkList.splice(index, 1) // 一旦上传成功就删除这一个 chunk,方便断点续传}else{this.$mseeage({type: "error",message: response.data.message})return }})}requestList.push(fn)})let i = 0 // 记录发送的请求个数// 文件切片全部发送完毕后,需要请求 '/merge' 接口,把文件名传递给服务器const complete = () => {axios({url: 'http://localhost/api/merge',method: 'get',params: {filename: this.fileName },timeout: 60000}).then(response => {if (response.data.errcode === 0) { // 请求发送成功// this.videoUrl = res.data.pathconsole.log(response.data)}})}const send = async () => {if (!this.upload) returnif (i >= requestList.length) {// 发送完毕complete()return}await requestList[i]()i++send()}send() // 发送请求this.emitInput(this.fileName)},// 按下暂停按钮handleClickBtn() {this.upload = !this.upload// 如果不暂停则继续上传if (this.upload) this.sendRequest()},// 将 File 对象转为 ArrayBuffer fileToBuffer(file) {return new Promise((resolve, reject) => {const fr = new FileReader()fr.onload = e => {resolve(e.target.result)}fr.readAsArrayBuffer(file)fr.onerror = () => {reject(new Error('转换文件格式发生错误'))}})}}}
</script><style scoped "">.progress-box {box-sizing: border-box;width: 360px;display: flex;justify-content: space-between;align-items: center;margin-top: 10px;padding: 8px 10px;background-color: #ecf5ff;font-size: 14px;border-radius: 4px;}.videoShow{width: 100%;height:600px;padding: 10px 0 50px;position: relative;
}
#videoBox{object-fit:fill;border-radius: 8px;display: inline-block;vertical-align: baseline;
}
.video-img{position: absolute;top: 0;bottom: 0;width: 100%;z-index: 999;background-size:100%;cursor:pointer;}
.video-img img {display:block;width: 60px;height: 60px;position: relative;top:260px;left: 48%;
}
video:focus {outline: -webkit-focus-ring-color auto 0px;}
</style>

二、后端java代码

String dirPath = "D:\\video\\train"
@PostMapping("/chunk")
public Result upLoadChunk(@RequestParam("chunk") MultipartFile chunk,@RequestParam("filename") String fileName) {// 用于存储文件分片的文件夹File folder = new File(dirPath);if (!folder.exists() && !folder.isDirectory())folder.mkdirs();// 文件分片的路径String filePath = dirPath + fileName;try {File saveFile = new File(filePath);// 写入文件中//FileOutputStream fileOutputStream = new FileOutputStream(saveFile);//fileOutputStream.write(chunk.getBytes());//fileOutputStream.close();chunk.transferTo(saveFile);return new Result();} catch (Exception e) {e.printStackTrace();}return new Result();
}@GetMapping("/merge")
public Result MergeChunk(@RequestParam("filename") String filename) {String preName = filename.substring(0,filename.lastIndexOf("."));// 文件分片所在的文件夹File chunkFileFolder = new File(dirPath);// 合并后的文件的路径File mergeFile = new File(dirPath + filename);// 得到文件分片所在的文件夹下的所有文件File[] chunks = chunkFileFolder.listFiles();System.out.println(chunks.length);assert chunks != null;// 排序File[] files = Arrays.stream(chunks).filter(file -> file.getName().startsWith(preName)).sorted(Comparator.comparing(o -> Integer.valueOf(o.getName().split("\\.")[0].split("_")[1]))).toArray(File[]::new);try {// 合并文件RandomAccessFile randomAccessFileWriter = new RandomAccessFile(mergeFile, "rw");byte[] bytes = new byte[1024];for (File chunk : files) {RandomAccessFile randomAccessFileReader = new RandomAccessFile(chunk, "r");int len;while ((len = randomAccessFileReader.read(bytes)) != -1) {randomAccessFileWriter.write(bytes, 0, len);}randomAccessFileReader.close();System.out.println(chunk.getName());chunk.delete(); // 删除已经合并的文件}randomAccessFileWriter.close();} catch (Exception e) {e.printStackTrace();}return new Result();
}

注意:

vue组件中导入的utils/index.js

/*** 获取uuid*/export function getUUID () {return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)})
}

vue上传大文件/视频前后端(java)代码相关推荐

  1. uni-app上传大文件/视频失败详解

    大文件/视频上传失败可能会给你造成一个跨域的假象,仔细分析一下,如果小文件/视频可以上传成功.就说明不是跨域的问题,可以排除跨域.就可能是一下三个原因造成大文件/视频上传失败. 原因一: APP做了上 ...

  2. 七牛云分片批量上传大文件视频

    原本用的element上传组件,结果发现大视频总是失败,还跑出outMemoryError :java heap space 内存溢出,排查:jvm内存默认256m,每次文件上传,用的是muiltip ...

  3. PHP上传大文件视频到阿里云oss分片上传

    下载阿里云oss的SDK composer require aliyuncs/oss-sdk-php 上传视频,我用的是分片上传,其实阿里云的文档已经写得很清楚了,不过这是当我把上传的功能写出来后才这 ...

  4. react+antd的Upload 通过证书 上传大文件视频至oss(上传视频)

    主要代码 1. form表单的upload组件引入<Form.Item label="上传视频">{getFieldDecorator('url', {getValue ...

  5. 【微信小程序分包上传大文件/视频】

    这不前两天来了个奇葩需求,我写的小视频平台人家要上传2个G以上的视频,一开始咋想都想不通怎么写,后来一下就茅厕顿开了属于是,话不多说直接上码! upload.js: var bytesPerPiece ...

  6. 华为云服务器 大文件,云服务器上传大文件

    云服务器上传大文件 内容精选 换一换 本节操作介绍本地MacOS系统主机通过安装"Microsoft Remote Desktop for Mac"工具向Windows云服务器传输 ...

  7. antd upload手动上传_SpringBoot 如何上传大文件?

    最近遇见一个需要上传超大大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现. 在某些业务中,大文件上传是一个比较重要的交互场景,如上传入库比较大的Excel表 ...

  8. 前端上传大文件怎么处理

    前端上传大文件怎么处理 - 掘金 背景 当我们在做文件的导入功能的时候,如果导入的文件过大,可能会导所需要的时间够长,且失败后需要重新上传,我们需要前后端结合的方式解决这个问题 思路 我们需要做几件事 ...

  9. SpringBoot如何上传大文件

    最近遇见一个需要上传超大大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现. 在某些业务中,大文件上传是一个比较重要的交互场景,如上传入库比较大的Excel表 ...

最新文章

  1. FPGA之道(58)关于外界接口的编程思路
  2. iptables与tomcat
  3. 一篇故事讲述了计算机网络里的基本概念:网关,DHCP,IP寻址,ARP欺骗,路由,DDOS等...
  4. matlab 城市间最短路径
  5. java的构造特点_JAVA学习第八课(构造函数及其特点)
  6. 世界之窗浏览器怎么隐藏收藏栏
  7. 项目管理系列之项目范围时间及资源管理(一)
  8. WEB前端性能优化常见方法
  9. HTML5 Geolocation(地理定位)用于定位用户的位置。
  10. Linux-----信号量
  11. 5.12 利用图层蒙版制作图像合成特效 [原创Ps教程]
  12. SpringCloud 问题杂集
  13. Linux收音机软件,在Linux终端听收音机
  14. 浅谈虚拟化软件再防泄密领域的表现如何
  15. Python一行代码搞定炫酷可视化,Cufflinks值得拥有 !
  16. HDU4355-三分
  17. 使用高德地图绘制矩形网格,显示行政区域。
  18. Linux服务器相关命令(更新中)
  19. 如何从ip服务器所用系统,如何从0开始打造一个深度学习服务器?
  20. plt作图时出现横坐标或者纵坐标乱序的解决方法

热门文章

  1. Python使用Google多语言翻译Excel文档
  2. 【Linux】CPU信息速查(品牌型号 | 物理CPU数 | 物理核数 | 逻辑核数)
  3. jqueryCutDown.js结合moment.js倒计时整理,直接copy可用,别忘了引入jquery
  4. SpringSecurity专题(五)-数据库认证
  5. 滤波器的知识点(一)
  6. 电脑坏了怎么把硬盘的mysql数据恢复_硬盘坏了怎么恢复数据?
  7. 设计一个最优算法来查找一n个元素数组中的最大值和最小值
  8. mac 安装win7 攻略
  9. Win10设置添加来宾账户的方法
  10. 观察 :人工智能与伦理道德