1
1
import { useEffect , useState } from "react" ;
2
2
import { type Paper } from "@/interface" ;
3
3
import Image from "next/image" ;
4
- import { Eye } from "lucide-react" ;
4
+ import { Eye , Download } from "lucide-react" ;
5
5
import {
6
6
extractBracketContent ,
7
7
extractWithoutBracketContent ,
8
8
} from "@/util/utils" ;
9
9
import { capsule } from "@/util/utils" ;
10
+ import axios from "axios" ;
10
11
import { useRouter } from "next/navigation" ;
11
12
import Link from "next/link" ;
12
13
@@ -26,11 +27,31 @@ const Card = ({
26
27
setChecked ( isSelected ) ;
27
28
} , [ isSelected ] ) ;
28
29
30
+ const handleDownload = async ( paper : Paper ) => {
31
+ const extension = paper . finalUrl . split ( "." ) . pop ( ) ;
32
+ const fileName = `${ extractBracketContent ( paper . subject ) } -${ paper . exam } -${ paper . slot } -${ paper . year } .${ extension } ` ;
33
+ await downloadFile ( paper . finalUrl , fileName ) ;
34
+ } ;
35
+
29
36
function handleCheckboxChange ( ) {
30
37
setChecked ( ! checked ) ;
31
38
onSelect ( paper , ! checked ) ;
32
39
}
33
40
41
+ async function downloadFile ( url : string , filename : string ) {
42
+ try {
43
+ const response = await axios . get ( url , { responseType : "blob" } ) ;
44
+ const blob = new Blob ( [ response . data ] ) ;
45
+ const link = document . createElement ( "a" ) ;
46
+ link . href = window . URL . createObjectURL ( blob ) ;
47
+ link . download = filename ;
48
+ link . click ( ) ;
49
+ window . URL . revokeObjectURL ( link . href ) ;
50
+ } catch ( error ) {
51
+ console . error ( "Error downloading file:" , error ) ;
52
+ }
53
+ }
54
+
34
55
function handleOpen ( ) {
35
56
const storedPapers = JSON . parse (
36
57
localStorage . getItem ( "clickedPapers" ) ?? "[]" ,
@@ -85,23 +106,14 @@ const Card = ({
85
106
</ div >
86
107
< div className = "flex gap-2" >
87
108
< Eye size = { 20 } className = "cursor-pointer" onClick = { handleOpen } />
88
- < button
89
- onClick = { ( ) => {
90
- const iframe = document . createElement ( "iframe" ) ;
91
- iframe . style . display = "none" ;
92
- iframe . src = paper . finalUrl ;
93
- document . body . appendChild ( iframe ) ;
94
- setTimeout ( ( ) => {
95
- document . body . removeChild ( iframe ) ;
96
- } , 1000 ) ;
97
- } }
98
- >
99
- Download
109
+ < button onClick = { ( ) => handleDownload ( paper ) } >
110
+ < Download size = { 20 } />
100
111
</ button >
101
112
</ div >
102
113
</ div >
103
114
</ div >
104
115
) ;
105
116
} ;
117
+ export const dynamic = 'force-dynamic'
106
118
107
119
export default Card ;
0 commit comments