简体   繁体   English

为什么前端说格式不正确

[英]Why frontend says that not well-formed

I try to get the file stream from my nodejs(express) backend,and download it using Range in Header.我尝试从我的 nodejs(express) 后端获取文件 stream,并使用 Header 中的 Range 下载它。 But the frontend says thatresponse is NOT WELL-FORMED, i can receive data from the back,but when i try to download it,its size is bigger than the real但是前端说响应不是很好,我可以从后面接收数据,但是当我尝试下载它时,它的大小比真实的要大

error:错误: 在此处输入图像描述

res data :资源数据: 在此处输入图像描述

Here is what i write in my node:这是我在节点中写的:

    console.log("handleDownload ")
    // 获取文件路径
    const fileId = req.query.id;
    let fileInfo, filePath, fileName;
    try {
        fileInfo = await FileList.findById(fileId, "meta", {
            lean: true
        })
        filePath = fileInfo.meta.resURL[0]
        fileName = fileInfo.meta.name
        fileType = fileInfo.meta.lftype
        
    } catch (e) {
        res.sendData("", 202, "数据库查找失败" + e)
        return
    }
    //let filePath = path.join(__dirname,'../uploads/',fileName);
    // 1、 判断文件是否存在
    try {
        fs.accessSync(filePath);
    } catch (error) {
        res.sendData("", 201, "下载的资源不存在" + error);
        return
    }
    try {
        // 获取文件大小
        console.log("range")
        const size = fs.statSync(filePath).size;
        const range = req.range();
        console.log(range)
        console.log("size:" + size)
        if (!range) {
            res.set(Object.assign({'Accept-Ranges': 'bytes'},createFileResHeader(fileName,size,fileType))).status(200).end()
        } else {
            const {
                start,
                end
            } = range[0]
            // 3、检查请求范围
            if (start >= size || end >= size) {
                res.status(416).set('Content-Range',`bytes */${size}`)
            } else {
                // 4、返回206:客户端表明自己只需要目标URL上的部分资源的时候返回的
                res.status(206).set('Content-Range',`bytes ${start}-${end ? end : size - 1}/${size}`)
                //.set('Content-Length',end-start+1)
            }
            //res.send()
            fs.createReadStream(filePath, {start, end}).pipe(res);
        }
    } catch (err) {
        res.send("", 201, err)
        return;
    }
};

And the header i receive is:我收到的 header 是:

HTTP/1.1 206 Partial Content
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Range: bytes 0-898656/898657
Date: Mon, 17 Jan 2022 11:58:21 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked

And my frontend code:还有我的前端代码:

axios({
            method: 'get',
            url: '/crud/download',
            params: {
                id: fileId,
            },
            headers: {
                Range: `bytes=${start}-${end}`, 
                responseType : "application/octet-stream"
            },
        }).then(res => {
            downloaded += end - start + 1
            if(downloaded < fileSize)  {
                download(fileId,fileName,fileSize,fileType,axios,msg,downloaded)
            }else {
                //console.log(fileType)
                const blob = new Blob([res.data],{type:fileType});
                const href = URL.createObjectURL(blob);
                //console.log(href)
                downloadEvt(href, fileName);
            }
        })
        .catch(e => {
            msg({
                msg: e
            })
        })

if-else part is the core code if-else 部分是核心代码

I can download the file but its size is bigger than the real,and surely can't open it.我可以下载文件,但它的大小比真实的大,肯定无法打开它。 I think it's relative to ( Transfer-Encoding: chunked )in response header.我认为它与响应 header 相关的(传输编码:分块)。 I can't resovle this problem,I'll appriciate if you give me some tips我无法解决这个问题,如果你给我一些建议,我会很高兴

Well,today i solve this problem.i set responseType = "blob" in axios req.i tried to set this before but i put it into req headers instead of as a single like this:好吧,今天我解决了这个问题。我在 axios req 中设置了 responseType = "blob"。我之前尝试设置它,但我将它放入 req 标头而不是像这样的单个:

axios({
            method: 'get',
            url: '/crud/download',
            params: {
                id: fileId,
            },
            headers: {
                Range: `bytes=${start}-${end}`,
            },
            responseType : 'blob',
        })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM