JS操作文件

169 阅读1分钟

这是我参与更文挑战的第9天,活动详情查看: 更文挑战

前言

一直以来前端对文件的操作能力都是有限的,在HTML5出现以前对文件操作基本是没有的。HTML5引入的File API让JS对文件的操作有了一个很大的进步。

本地文件上传预览

在H5出现以前,预览本地文件只能通过上传后端,然后生成一个URL来提供给前端。HTML5出现以后,通过BlobURL.createObjectURL可以实现前端对本地文件的预览。

function uploadFile() {
    const materialPic = document.getElementById('materialPic')
    let fileName = materialPic.files[0]
    const blob = new Blob([fileName])
    
    //预览url
    let url = URL.createObjectURL(blob);
}

文件下载

HTML5为a标签提供了一个download属性来支持文件的下载。

import axios from 'axios'

function downloadFun(url, name='download') {
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.href = url
    eleLink.click()
    eleLink.remove()
}


// 通过ajax请求,获得文件的blob数据
export function downloadByGetBlob (url, name) {
    axios.get(url, {     
        responseType: 'blob'
    }).then(res => {
        let data = res.data

        let blobUrl = URL.createObjectURL(data)
        downloadFun(blobUrl, name)
        URL.revokeObjectURL(blobUrl)
    }).catch(() => {
        ...
    })
}
  1. 上传文件后输入框重置

input[type=file]上传文件时,当两次上传的文件相同时,onChange事件是无法触发的。这样导致交互体验很不好,可以通过

方案一:使用form表单重置页面(适用于未使用表单提交数据的页面,以免影响别的表单控件)

function resetInput(f) {
    let form = document.createElement('form')
    let parent = f.parentNode
    form.appendChild(f)
    form.reset()
    parent && parent.appendChild(f)
}

方案二:将input的value值设置为空

document.getElementById('uploadInput').value = null;
  1. 判断上传文件内容是否合法

在上传文件前可以对文件大小,文件内容等做一些基础的验证。

function addTxtUser() {
    this.temp.toUser = []
    let self = this
    let user = document.getElementById('user_txt')
    let user_txt = user.files[0]

    let size = user_txt.size/1024
    if (size > 5000) {
        self.$message({
            message: '文件不能大于5M',
            type: 'error'
        })
        return
    }
    let reader = new FileReader()
    reader.readAsText(user_txt)

    reader.onload = function() {
        ...验证内容
    }

    resetInput(user)
}