我被赋予了从.srt文件中删除某些非打印字符的任务,并按照以下方式进行操作。 1)导入文件
2)将文件作为文本读取
3)使用RegEx替换非打印字符
4)将文本转换回文件并附加到锚标记中的href属性以供下载。
请检查我的方法。
但是,将dataURL传递给href属性的步骤似乎不起作用。我的console.log语句显示了一个dataURL但由于某种原因它没有被传递给href属性。当我下载文件并打开它时,它是一个空白文件,只是说“未定义”。
请指教
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.uploadFile = this.uploadFile.bind(this);
}
uploadFile(e) {
let file = e.target.files[0];
if(file) {
console.log(file);
let textReplaced;
let originalFileAsText;
let output;
//var aTag1 = document.getElementById('original');
var aTag2 = document.getElementById('modified');
const reader1 = new FileReader();
reader1.onload = function(event) {
console.log(event.target.result);
originalFileAsText = reader1.result;
textReplaced = originalFileAsText.replace(/\r\n(?=\r\n)(?=^\d+$)/g, /\n/);
}
reader1.readAsText(file);
output = new File([textReplaced], "", {type: "text/plain"})
console.log(output);
const reader2 = new FileReader();
reader2.onload = function(event) {
console.log("result --->", reader2.result);
console.log("eTargetRes--->",event.target.result);
aTag2.href = reader2.result;
console.log(aTag2.href)
}
reader2.readAsDataURL(output);
}
}
render() {
return (
<div className="App">
<input type="file"
name="og"
onChange={this.uploadFile}/>
<div id="text-container" style={{"display" : "flex", "flexDirection" : "row", "justifyContent" : "space-evenly"}}>
<a href="" download="original_file.srt" style={{"width":"200px"}} id="original" name="original" alt="original"> uploaded file </a>
<a href="" download="modified_file.txt" style={{"width":"200px"}} id="modified" name="modified" alt="modified"> modified file </a>
</div>
</div>
);
}
}
export default App
This example似乎工作得很好。请记住FileReader
做its work asynchronously。您应该等到设置第二个阅读器,直到完成第一个阅读器。
在这种情况下,控制台日志记录会产生误导。这是uploadFile方法的清理版本供考虑。这有点副作用,但它更简单,更有效。
uploadFile(e) {
let file = e.target.files[0];
if(file) {
const reader = new FileReader();
const setResultAsHref = (event) => {
const aTag2 = document.getElementById('modified');
aTag2.href = event.target.result;
}
const convertResultAndSetHref = (event) => {
const originalFileAsText = event.target.result;
const textReplaced = originalFileAsText.replace(/\r\n(?=\r\n)(?=^\d+$)/g, /\n/);
const output = new File([textReplaced], "", {type: "text/plain"})
event.target.onload = setResultAsHref
event.target.readAsDataURL(output);
}
reader.onload = convertResultAndSetHref;
reader.readAsText(file);
}
}