在React前端应用程序中接收文件内容

问题描述 投票:0回答:1

我的

NodeJS
应用程序中有一个 API 端点。我向其发布文件名以查找文件夹中的特定文件。我这样做是这样的:

const fileDirectory = 'C:/Sites/private-uploads';
try {
    // Extract filename from request parameters or query string
    const body = ctx.request.body; // Assuming filename is passed as a parameter in the route
    const filename = body.data.filename;

    // Check if the file exists
    const filePath = path.join(fileDirectory, filename);
    console.log(filePath);
    if (!fs.existsSync(filePath)) {
        ctx.status = 404;
        ctx.body = { error: 'File not found' };
        return;
    }

    // Read the file contents as raw binary data
    const fileContents = await fs.readFile(filePath, null); // Passing null as the encoding parameter
    const fileSizeKB = fileContents.length / 1024; // Convert bytes to kilobytes
    console.log('File size:', fileSizeKB.toFixed(2), 'KB');

    // Set appropriate headers
    ctx.set('Content-Type', 'application/octet-stream'); // Set Content-Type to indicate binary data
    ctx.set('Content-Disposition', `attachment; filename="${filename}"`); // Set filename for download

    // Send the file contents as the response body
    ctx.body = fileContents;
} catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { error: 'Error retrieving file contents' };
}

当执行

console.log
文件大小时,它会显示正确的文件大小。

在我的 React 应用程序中,我收到如下文件:

const getFile = async (filename) => {
        try {
            const response = await api.post('/api/get-file', {
                data: {
                    filename: filename
                }
            });
            if (response.data) {
                console.log(response.data);
                const blob = new Blob([response.data]);
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }
        } catch (error) {
            console.log(error);
        }
    }

它返回给我一个文件,但它的文件大小更大并且无法打开该文件。 有人看到我在这里做错了什么吗?

javascript reactjs node.js readfile node.js-fs
1个回答
0
投票

嗯,我建议重新检查服务器端代码并确保命名匹配,因为当您从客户端请求文件大小时,文件大小不应更改。

© www.soinside.com 2019 - 2024. All rights reserved.