res.download()问题

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

我在尝试将 res.download(filePath,originalName) 与 Multer 一起应用时遇到问题,因为当我将逻辑应用于它时,它会使用 fs.copyFile() 将文件从 /uploads 文件夹保存/复制到 /downloads 但是,对于在目标客户端,您不会收到允许您保存文件的浏览器打开信息。

有什么想法吗?在前面,我没有收到任何东西...我的请求是否错误?谢谢!

要求:

server.get('/download/:fileId', downloadFileHandler)

下载文件处理程序:

export default async (req, res, next) => {
    const token = req.headers.authorization.substring(7)
    const { sub: userId } = jwt.verify(token, process.env.JWT_SECRET)

    const { fileId } = req.params

    try {
        const file = await downloadFile(userId, fileId)
        const { path, originalName } = file

        res.download(path, originalName)
    } catch (error) {
        let status = 500
............REST CODE ERROR...............


下载文件逻辑:

export default async function downloadFile(userId, fileId) {

    try {
        const user = await User.findById(userId).lean()
        if (!user) {
            throw new NotFoundError('User not found')
        }

        const file = await File.findById(fileId).lean()
        if (!file) {
            throw new NotFoundError('File not found')
        }

        // const isOwner = user.id === file.owner
        // const isAdmin = user.role && user.role.includes('admin')

        if (file.owner[0] === user.id || user.role[0] === 'admin') {
            const originalName = file.name
            const oldPath = `./uploads/${file._id.toString()}`
            const newPath = `./downloads/${originalName}`

            await fs.copyFile(oldPath, newPath)

            return { path: newPath, originalName }
        } else {
            throw new AuthorizationError('Authorization denied. Try again')
        }

    } catch (error) {


使用 MULTER 的 res.download() 解决方案

node.js mongodb download backend node.js-fs
1个回答
0
投票

我可以用 .blob() 方法解决这个转换文件数据的问题。

这是我的代码:

函数句柄下载文件(事件){ event.preventDefault()

const clientError = document.querySelector(props.clientError)

try {
    logic.downloadFile(file.id)
        .then(blob => {
            const url = window.URL.createObjectURL(blob)

            const anchor = document.createElement('a')
            anchor.href = url
            anchor.download = file.name
            anchor.click()

            window.URL.revokeObjectURL(url)

            clientError.innerText = 'File successfully download ✅'
            clientError.style.color = 'green'
        })
} catch (error) {
    clientError.innerText = `${error.message} ❌`
    clientError.style.color = 'tomato'

    handleError(error, navigate)
}
© www.soinside.com 2019 - 2024. All rights reserved.