This article mainly shares with you the code for uploading and previewing txt files in js. Because it is a simple txt file, it only involves text. If you need to preview images, you need to use papaparse and jschardet. There is not much description here.
The form button uses the onchange="uploadfile()" event of js. The function function code is as follows:
//此处为txt文件上传预览的js代码function uploadfile(){ var file=$("#txt")[0].files[0]; //判断上传文件是不是txt格式,判断后缀是不是.txt if(file.name.substr(-4).toLocaleLowerCase() != '.txt'){ alert("请上传格式为txt的文件!"); windows.location="test.jsp";//重新定位到上传txt文件页面 } else//如果上传文件是txt文件,则显示文件的预览 { var reader=new FileReader; reader.readAsText(file,'gb2312'); //reader.readAsDataURL(file); reader.onload=function(evt){ var data=evt.target.result; $('#textarea_id').val(data); } } }
The effect is as follows:
#I happened to come across this record while working on a project today. Because it is a simple txt file, it only involves text. If you need to preview images, you need to use papaparse and jschardet. There is not much description here.
The form button uses the onchange="uploadfile()" event of js. The function function code is as follows:
//此处为txt文件上传预览的js代码function uploadfile(){ var file=$("#txt")[0].files[0]; //判断上传文件是不是txt格式,判断后缀是不是.txt if(file.name.substr(-4).toLocaleLowerCase() != '.txt'){ alert("请上传格式为txt的文件!"); windows.location="test.jsp";//重新定位到上传txt文件页面 } else//如果上传文件是txt文件,则显示文件的预览 { var reader=new FileReader; reader.readAsText(file,'gb2312'); //reader.readAsDataURL(file); reader.onload=function(evt){ var data=evt.target.result; $('#textarea_id').val(data); } } }
The effect is as follows:
Related recommendations:
Example of PHP method of reading txt file line by line
The above is the detailed content of js code for uploading and previewing txt files. For more information, please follow other related articles on the PHP Chinese website!