Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  180] [ 4]  / answers: 1 / hits: 35090  / 5 Years ago, tue, march 19, 2019, 12:00:00

I am using the Ant Design Upload component. Is there a way I can get the content of the selected file as a string in JavaScript in order to display it on the page?



Ideally, I would like to access file.data or something.



<Upload
accept=.txt, .csv
showUploadList={false}
beforeUpload={(file, fileList) => {
// Access file content here and do something with it
console.log(file);

// Prevent upload
return false;
}}
>
<Button>
<Icon type=upload /> Click to Upload
</Button>
</Upload>

More From » reactjs

 Answers
28

Heavily inspired by this answer from Shreyans Shrivastav but modified to better suit what has been asked. You can use a FileReader to read the content of the file:



<Upload
accept=.txt, .csv
showUploadList={false}
beforeUpload={file => {
const reader = new FileReader();

reader.onload = e => {
console.log(e.target.result);
};
reader.readAsText(file);

// Prevent upload
return false;
}}
>
<Button>
<Icon type=upload /> Click to Upload
</Button>
</Upload>;

[#52403] Wednesday, March 13, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;