js上传文件并预览文件内容
1.獲取文件內(nèi)容:
selectFile = (e) => {
? ? ? ? const file = e.target.files[0];
? ? ? ? console.log('file>>>>',file);//此時發(fā)現(xiàn)找不到文件內(nèi)容
? ? ? ? if (!!file) {
? ? ? ? ? ? // 使用 FileReader 來讀取文件
? ? ? ? ? ? let reader = new FileReader()
? ? ? ? ? ? // 讀取純文本文件,且編碼格式為 utf-8
? ? ? ? ? ? reader.readAsText(file, 'UTF-8')
? ? ? ? ? ? //圖片類: reads.readAsDataURL(file);
? ? ? ? ? ? // 讀取文件,會觸發(fā) onload 異步事件,可使用回調(diào)函數(shù) 來獲取最終的值.
? ? ? ? ? ? reader.onload = function (e) {
? ? ? ? ? ? ? ? let fileContent = e.target.result//圖片類可將此值賦給img.src
? ? ? ? ? ? ? ? console.log('fileContent>>>>',fileContent)
? ? ? ? ? ? }
? ? ? ? }
? ? }
2.上傳文件:
<input className="upload_ipt" type="file" id="file" onChange={(e)=>{this.selectFile(e)}}></input>
selectFile = (e) => {
? ? ? ? const file = e.target.files[0];
? ? ? ? const max_size = 1024 * 1024 * 20
? ? ? ? if(file.size <= max_size){
? ? ? ? ? ? if(/.(jpg|png|fpx|svg|psd)$/.test(file.name)){
? ? ? ? ? ? ? ? const data = new FormData();
? ? ? ? ? ? ? ? data.append('file', file);
? ? ? ? ? ? ? ? Upload(data).then((res)=>{
? ? ? ? ? ? ? ? ? ? const resdata = res.data
? ? ? ? ? ? ? ? ? ? if (resdata.code === 0) {
? ? ? ? ? ? ? ? ? ? ? ?......
? ? ? ? ? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? ? ? ? ? alert("其它原因錯誤")
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }).catch((error)=>{
? ? ? ? ? ? ? ? ? ? console.log("axios catch error:",error)
? ? ? ? ? ? ? ? ? ? alert("服務(wù)端錯誤")
? ? ? ? ? ? ? ? })
? ? ? ? ? ? }else{alert("上傳圖片必須是jpg/png/fpx/svg/psd格式!")}
? ? ? ? }else{alert("文件大小不能超過20M")}
? ? }
總結(jié)
以上是生活随笔為你收集整理的js上传文件并预览文件内容的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 吹牛
- 下一篇: 排序算法时间复杂度、空间复杂度、稳定性比