首页 > 其他分享 >js实现大文件分片上传

js实现大文件分片上传

时间:2023-11-14 10:23:55浏览次数:25  
标签:const chunk js currentChunkIndex file 分片 chunks 上传

简单的实现一个分片上传

// 设置分片大小(大小根据需求调整)
const CHUNK_SIZE = 1024 * 1024; // 1MB

// 选择文件并切割成分片
const fileInput = document.getElementById('file-input');
const chunks = [];
let currentChunkIndex = 0;

fileInput.addEventListener('change', handleFileInputChange);

function handleFileInputChange(event) {
const file = event.target.files[0];
splitFileIntoChunks(file);
uploadFileChunks();
}

function splitFileIntoChunks(file) {
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

for (let i = 0; i < totalChunks; i++) {
const start = i * CHUNK_SIZE;
const end = start + CHUNK_SIZE;
const chunk = file.slice(start, end);
chunks.push(chunk);
console.log('chunk',chunk,chunks);
}
}
// 上传分片
function uploadFileChunks() {
if (currentChunkIndex >= chunks.length) {
console.log('All chunks uploaded!');
return;
}

const formData = new FormData();
formData.append('chunk', chunks[currentChunkIndex]);
// 第几片
formData.append('index', currentChunkIndex);
// 总片数
formData.append('totalChunks', chunks.length);

// 使用 XMLHttpRequest 或 Fetch API 进行异步上传分片
// 在每个请求的回调函数中继续上传下一个分片

// 示例使用 Fetch API 发送请求
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
if(currentChunkIndex === chunks.length - 1){
console.log('Uploaded all chunks!');
}else{
currentChunkIndex++;
uploadFileChunks(); // 继续上传下一个分片
}
} else {
console.log('Chunk upload failed.');
}
})
.catch(error => {
console.log(`Error uploading chunk: ${error}`);
});
}

 

参考文章:http://blog.ncmem.com/wordpress/2023/11/14/js%e5%ae%9e%e7%8e%b0%e5%a4%a7%e6%96%87%e4%bb%b6%e5%88%86%e7%89%87%e4%b8%8a%e4%bc%a0/

欢迎入群一起讨论

 

 

标签:const,chunk,js,currentChunkIndex,file,分片,chunks,上传
From: https://www.cnblogs.com/songsu/p/17831021.html

相关文章

  • js---判断用户是否在浏览当前页面
    最近遇到一个需求,需要判断用户是否在当前页面,只有用户在当前页面才可以播放视频,如果切换到其他窗口就要将视频暂停掉,避免学生刷课程,以下是具体的代码:<scripttype="text/javascript"src="js/jquery-1.8.3.min.js"></script><scripttype="text/javascript">varindex=0,ti......
  • 来来来,一文让你读懂Cocos Creator如何读写JSON文件
    前言在游戏开发过程中,读取配置文件是必不可少的,而使用JSON做配置文件又比较常见,本文重点给大家讲述如何在CocosCreator开发中读取和解析JSON数据文件以及如何写JSON文件。一、JSON简介1.什么是JSONJSON的英文全称是JavaScriptObjectNotation,即JavaScript对象表示法。2.J......
  • Python Object of type float32 is not JSON serializable
    前言使用json.dumps(result)对数据转JSON数据出现错误:TypeError:Objectoftypefloat32isnotJSONserializable数据中存在的float32数据是numpy格式的数据,Python内置的float类型可以写入JSON中,但是numpy的float32类型数据不能写入JSON,所以应将numpy.flo......
  • utils.js
    //获取连接参数值getUrlParams(name){varreg=newRegExp('(^|&)'+name+'=([^&]*)(&|$)','i')varr=window.location.search.substr(1).match(reg)if(r!=null){retur......
  • js实现分割上传大文件
    本文实例介绍了js上传文件操作,分享给大家供大家参考,具体内容如下<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"lang="zh-CN">&l......
  • uniapp(安卓)之文件上传
    uniapp(安卓)之文件上传uniapp提供的uni.chooseFile只支持H5和微信小程序,所以想上传除图片/视频外的非媒体文件,需要使用原生的方式开发。 uploadtxdr(){//使用plus选择文件 letthat=this; letfilePath='' letmain=plus.android.runtimeMainAct......
  • Newtonsoft.Json 入门介绍
    本人是C#小白,这里摘抄并整理了两位大神的文章:Newtonsoft.Json笔记-JToken、JObject、JArray详解Json基于类Newtonsoft.Json.Linq.JToken的应用简介 简单介绍如何使用Newtonsoft.Json类库和操作Json对象,这里主要介绍LinqtoJson类。Newtonsoft.Json封装类实现了JToken,直......
  • Python | 将本地文件上传到远程服务器
    在Python中,可以使用paramiko库来通过SSH进行文件的传输。首先,你需要安装paramiko库,可以使用以下命令进行安装:pipinstallparamiko然后,你可以使用以下Python脚本进行文件传输:此脚本使用SFTP协议进行文件传输。在SFTP的上下文中,你可以使用put方法将本地文件上传到远程服务器。......
  • vuejs3.0 从入门到精通——Vuex 4.x —— Getter
    Vuex4.x——Getterhttps://vuex.vuejs.org/zh/guide/getters.html 有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并计数:computed:{doneTodosCount(){returnthis.$store.state.todos.filter(todo=>todo.done).length}} 如......
  • 使用PageHelper.startPage时 net.sf.jsqlparser.parser.ParseException: Encountered
    使用PageHelper.startPage时net.sf.jsqlparser.parser.ParseException:Encountered解决方案对比代码:原来的写法:PageHelper.startPage(page,size,order);List<xxx>list=xxxMapperExt.selectxxx(id,type);修改之后:PageHelper.startPage(page,size);List<xxx>list=xxxM......