김재형

Implement file download

import React, { Fragment } from "react";
import React from "react";
import { FileItem } from "./useFileList";
import { Link } from "react-router-dom";
import { Button } from "antd";
import { FolderFilled, FileFilled } from "@ant-design/icons";
import { useDownload } from "./useDownload";
export function FileListItem({ item }: { item: FileItem }) {
const download = useDownload();
return item.is_folder ? (
<Fragment>
<Link to={`/folder/${item.id}`}>
<FolderFilled /> {item.name}
</Link>
</Fragment>
<Link to={`/folder/${item.id}`}>
<FolderFilled /> {item.name}
</Link>
) : (
<Fragment>
<Button
type="link"
size="small"
onClick={() => download(item.id)}
style={{ padding: 0 }}
>
<FileFilled /> {item.name}
</Fragment>
</Button>
);
}
......
import { useApi } from "util/useApi";
import { useCallback } from "react";
function downloadURL(url: string, name: string) {
const link = document.createElement("a");
link.setAttribute("download", name);
link.href = url;
link.target = "_blank";
link.click();
}
export function useDownload() {
const api = useApi();
const download = useCallback(
async (id: number) => {
const response = await api.get(`/items/${id}/`).json<any>();
const { signed_url, name } = response.data;
downloadURL(signed_url, name);
},
[api]
);
return download;
}