2024年vue3多文件大文件分片上传(spark-md5),2024年最新高级Web前端开发面试解答之线程篇

js基础

1)对js的理解?
2)请说出以下代码输出的值?
3)把以下代码,改写成依次输出0-9
4)如何区分数组对象,普通对象,函数对象
5)面向对象、面向过程
6)面向对象的三大基本特性
7)XML和JSON的区别?
8)Web Worker 和webSocket?
9)Javascript垃圾回收方法?
10)new操作符具体干了什么呢?
11)js延迟加载的方式有哪些?
12)WEB应用从服务器主动推送Data到客户端有那些方式?

js基础.PNG

前16.PNG

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

file: Blob
hash: string
chunkIndex: number
chunkCount: string
fileName: string
}


五、储存的变量



// 已上传文件列表
const filesList = ref<NewFileType[]>([])
// 切片默认大小
let chunkSize = 1024 * 1024 * 5
// 上传文件切片列表
const filesSliceList = ref<FileSliceListType[]>([])


六、选择文件



// 选择文件
const choiceFileHandle = (e:Event) => {
if (uploadLoading.value) return
if (!e.target) return
choiceInputValue.value = null
const files = Array.prototype.slice.call((e as HTMLInputEvent).target.files)
const newFileList = […filesList.value, …files]
// 记得再次添加去重
// removeDuplicateObj是业务逻辑的去重
filesList.value = removeDuplicateObj(newFileList)
}


七、文件分片及查询已上传的分片



// 查询已上传的切片
const queryUploadFileHandle = async(file:NewFileType, hash:string) => {
let isRepeat = false
await queryUploadFlilePost({ hash }).then((res) => {
if (res.code !== 200) {
ElMessage.error(res.msg)
return
}
const resultList = res?.data?.resultList
// 当前文件大小
const fileSize = file.size
// 当前文件分割多少份 (chunkSize 多少大小分割)
let chunkCount = Math.ceil(fileSize / chunkSize)
if (fileSize > chunkSize * 40) {
chunkSize = chunkSize * 8
chunkCount = Math.ceil(fileSize / chunkSize)
}

for (let i = 0; i < chunkCount; i++) {
  // 当前 分割 开始点
  const startPoint = i \* chunkSize
  // 当前分割 结束点
  const endPoint = Math.min(startPoint + chunkSize, fileSize)
  const chunk = file.slice(startPoint, endPoint)
  // 存储分片状态
  filesSliceList.value.push({
    file: chunk,
    chunkCount: chunkCount.toString(),
    fileName: file.name,
    hash,
    chunkIndex: i
  })
}

if (resultList && resultList.length !== 0) {
  // 切片数组排除已上传的切片
  for (let i = 0; i < filesSliceList.value.length; i++) {
    const item:FileSliceListType = filesSliceList.value[i]
    if (item.hash === hash && resultList.includes(String(item.chunkIndex))) {
      filesSliceList.value.splice(i, 1)
      i--
    }
  }

  if (filesSliceList.value.length === 0) {
    isRepeat = true
  }
}

})
return isRepeat
}


八、所有文件分片同时上传



const promiseArr: unknown[] = []
// 全部上传
const allUploadHandle = async() => {
for (const file of filesList.value) {
if (file.hash) continue
const hash = await getFileMD5(file) as string
file.state = {
state_txt: ‘load’,
tips_txt: ‘处理中,请稍后’
}
file.hash = hash
file.progress = 0
file.speep = 0
// 文件切片处理及跳过已上传分片
const curFileIsRepeat = await queryUploadFileHandle(file, hash)
if (curFileIsRepeat) {
file.state = {
state_txt: ‘success’,
tips_txt: ‘上传成功!’
}
file.progress = 100
continue
}

file.state.tips_txt = '上传中,请稍后'

}

// 循环调用切片上传
for (const fileSlice of filesSliceList.value) {
const curFileIndex = filesList.value.findIndex(item => item.hash === fileSlice.hash)
const curFile = filesList.value[curFileIndex]
if (curFile.state.state_txt === ‘success’) continue
fileSliceUploadHandle(fileSlice)
}

Promise.all(promiseArr).then(() => {
const newFileList = filesList.value
for (let i = 0; i < newFileList.length; i++) {
const item = newFileList[i]
if (item.state.state_txt === ‘error’ || item.state.state_txt === ‘load’) {
nextBtnTips.value = ‘请删除上传失败的内容!’
nextBtnDisabled.value = true
} else {
nextBtnDisabled.value = false
}
}
}).catch((err) => {
console.log(‘文件上传失败:’, err)
// 。。。。。失败处理
})
}

// 文件切片上传
const fileSliceUploadHandle = (fileChunk:FileSliceListType) => {
const curFileIndex = filesList.value.findIndex(item => item.hash === fileChunk.hash)
const curFile = filesList.value[curFileIndex]
const { chunkCount, chunkIndex, file, fileName, hash } = fileChunk
const curPromise = new Promise((resolve, reject) => {
uploadDigFlie({
fileName,
file,
chunkIndex,
hash,
chunkCount
}).then(res => {
if (res.code !== 200) {
ElMessage.error(res.msg)
return reject(res.msg)
}
curFile.speep = 100 / Number(chunkCount)
curFile.progress += curFile.speep
if (curFile.progress > 100) {
curFile.progress = 100
}
if (Math.ceil(curFile.progress) >= 100) {
curFile.state = {
state_txt: ‘success’,
tips_txt: ‘上传成功!’
}
}
return resolve(true)
})
})
promiseArr.push(curPromise)
}


九、下一步(对应合并所有分片)



const nextPromiseArr: unknown[] = []
// 下一步
const goNextHanlde = () => {
if (nextBtnDisabled.value) return
uploadLoading.value = true
let allFileId = ‘’
for (let i = 0; i < filesList.value.length; i++) {
const item = filesList.value[i]
const index = i
// 合并过的文件跳过合并
if (item.isMerge) continue
nextPromiseArr[index] = new Promise((resolve) => {
mergechunkFilePost({
fileName: item.name,
hash: item.hash
}).then(res => {
if (res.code !== 200) {
ElMessage.error(res.msg)
item.isMerge = false
return resolve(true)
}
// 增加合并过标识
item.isMerge = true
return resolve(true)
})
})
}
Promise.all(nextPromiseArr).then(() => {
uploadLoading.value = false
const newFileList = filesList.value
for (let i = 0; i < newFileList.length; i++) {
const item = newFileList[i]
if (!item.isMerge) {
newFileList[i].state = {
state_txt: ‘error’,
tips_txt: ‘上传失败原因:内容重复!’
}
filesList.value = newFileList
GetCurrentInstance && GetCurrentInstance.proxy?.$forceUpdate()
return
}
ES6

  • 列举常用的ES6特性:

  • 箭头函数需要注意哪些地方?

  • let、const、var

  • 拓展:var方式定义的变量有什么样的bug?

  • Set数据结构

  • 拓展:数组去重的方法

  • 箭头函数this的指向。

  • 手写ES6 class继承。

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

微信小程序

  • 简单描述一下微信小程序的相关文件类型?

  • 你是怎么封装微信小程序的数据请求?

  • 有哪些参数传值的方法?

  • 你使用过哪些方法,来提高微信小程序的应用速度?

  • 小程序和原生App哪个好?

  • 简述微信小程序原理?

  • 分析微信小程序的优劣势

  • 怎么解决小程序的异步请求问题?

其他知识点面试

  • webpack的原理

  • webpack的loader和plugin的区别?

  • 怎么使用webpack对项目进行优化?

  • 防抖、节流

  • 浏览器的缓存机制

  • 描述一下二叉树, 并说明二叉树的几种遍历方式?

  • 项目类问题

  • 笔试编程题:

最后

技术栈比较搭,基本用过的东西都是一模一样的。快手终面喜欢问智力题,校招也是终面问智力题,大家要准备一下一些经典智力题。如果排列组合、概率论这些基础忘了,建议回去补一下。

webpack的loader和plugin的区别?

  • 怎么使用webpack对项目进行优化?

  • 防抖、节流

  • 浏览器的缓存机制

  • 描述一下二叉树, 并说明二叉树的几种遍历方式?

  • 项目类问题

  • 笔试编程题:

最后

技术栈比较搭,基本用过的东西都是一模一样的。快手终面喜欢问智力题,校招也是终面问智力题,大家要准备一下一些经典智力题。如果排列组合、概率论这些基础忘了,建议回去补一下。

  • 19
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个示例代码,使用SpringMVC和Vue实现大文件分片上传,同时前端加入MD5校验,使用ElementUI实现进度条显示。 前端代码: ```vue <template> <div> <el-upload class="upload-demo" action="/upload" :before-upload="beforeUpload" :on-progress="onProgress" :on-success="onSuccess" :file-list="fileList"> <el-button type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传不超过 200MB 的文件</div> </el-upload> <el-progress :percentage="percentage" :stroke-width="30" :text-inside="true"></el-progress> </div> </template> <script> import SparkMD5 from 'spark-md5' export default { data() { return { fileList: [], percentage: 0, } }, methods: { beforeUpload(file) { return new Promise((resolve, reject) => { const reader = new FileReader() const chunkSize = 2 * 1024 * 1024 // 分片大小为2MB const chunks = Math.ceil(file.size / chunkSize) const spark = new SparkMD5.ArrayBuffer() let currentChunk = 0 reader.onload = e => { spark.append(e.target.result) currentChunk++ if (currentChunk < chunks) { loadNext() } else { file.md5 = spark.end() resolve(file) } } reader.onerror = () => { reject('读取文件出错') } function loadNext() { const start = currentChunk * chunkSize const end = Math.min(start + chunkSize, file.size) reader.readAsArrayBuffer(file.slice(start, end)) } loadNext() }) }, onProgress(e) { this.percentage = e.percent }, onSuccess(response, file) { this.percentage = 0 this.fileList = [] this.$message.success('上传成功') }, }, } </script> ``` 在这个示例代码中,我们使用了SparkMD5库来计算文件MD5,同时在`beforeUpload`方法中,将文件分成多个2MB的分片进行上传,以实现大文件分片上传MD5校验。在上传过程中,我们使用了ElementUI的进度条组件来显示上传进度。 后端代码: ```java @Controller public class UploadController { private static final String UPLOAD_DIR = "/tmp/uploads/"; private static final int CHUNK_SIZE = 2 * 1024 * 1024; @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file, @RequestParam("md5") String md5, @RequestParam(value = "chunk", required = false, defaultValue = "0") int chunk, @RequestParam(value = "chunks", required = false, defaultValue = "1") int chunks) throws IOException { String fileName = file.getOriginalFilename(); String filePath = UPLOAD_DIR + fileName; if (chunk == 0) { // 如果是第一个分片,检查文件是否存在,如果存在则直接返回 File f = new File(filePath); if (f.exists()) { return ResponseEntity.status(HttpStatus.OK).build(); } } else { // 如果不是第一个分片,检查文件是否存在,如果不存在则返回错误 File f = new File(filePath); if (!f.exists()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件不存在"); } } if (chunk == 0) { // 如果是第一个分片,创建文件 File f = new File(filePath); if (!f.getParentFile().exists()) { f.getParentFile().mkdirs(); } f.createNewFile(); } // 写入分片数据 RandomAccessFile raf = new RandomAccessFile(filePath, "rw"); raf.seek(chunk * CHUNK_SIZE); raf.write(file.getBytes()); raf.close(); if (chunk == chunks - 1) { // 如果是最后一个分片,检查文件MD5值是否正确,如果正确则合并文件 String fileMd5 = getFileMd5(filePath); if (!fileMd5.equals(md5)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件MD5值不正确"); } mergeFileChunks(filePath, chunks); } return ResponseEntity.status(HttpStatus.OK).build(); } private String getFileMd5(String filePath) throws IOException { InputStream fis = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int numRead; MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } do { numRead = fis.read(buffer); if (numRead > 0) { md5.update(buffer, 0, numRead); } } while (numRead != -1); fis.close(); byte[] md5Bytes = md5.digest(); StringBuilder sb = new StringBuilder(); for (byte b : md5Bytes) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } private void mergeFileChunks(String filePath, int chunks) throws IOException { File f = new File(filePath); FileOutputStream fos = new FileOutputStream(f, true); byte[] buffer = new byte[1024]; for (int i = 0; i < chunks; i++) { String chunkFilePath = filePath + "." + i; File chunk = new File(chunkFilePath); FileInputStream fis = new FileInputStream(chunk); int numRead; while ((numRead = fis.read(buffer)) > 0) { fos.write(buffer, 0, numRead); } fis.close(); chunk.delete(); } fos.close(); } } ``` 在后端代码中,我们使用了`RandomAccessFile`来实现文件分片写入和合并,同时在文件合并前使用了`getFileMd5`方法来检查文件MD5值是否正确。 最后,我们还需要在SpringMVC的配置文件中添加以下配置,以支持大文件上传: ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="209715200" /> <property name="maxInMemorySize" value="4096" /> </bean> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值