首页 > 解决方案 > Web 服务器将图像保存为 0 字节

问题描述

当我通过 http 请求将图像发送到我的网络服务器时,它会设法保存原始图像的完整尺寸。但是当我尝试调整图像大小时,它会将其保存为 0 字节。我使用一个名为 sharp 的 npm 模块来调整图像大小。当我在本地机器上进行任何调整大小,甚至是大规模调整大小的工作时,都没有问题。在我的 Apache Web 服务器上运行此代码会导致它在大多数情况下实际上并未保存图像。它实际保存的图像似乎完全随机。唯一一致的部分是它保存了通过http请求发送的原始图像。

在我的文件系统中会有原始图像 EG:abcdefg.jpg,然后 abcdefg-350x350.jpg 将是 0 字节。

        const results = await temp.mv(path.resolve(folderName + name + '.' + extension))

        bluebird.map(sizes, (size) => {
            sharp(folderName + name + '.' + extension)
                .resize(size.w, size.h, {
                    fit: 'cover'
                })
                .toFile(folderName + name + '-' + size.w + 'x' + size.h + '.' + extension)
            console.log('Resized image')
        })
        .then(() => {
            console.log('Images were resized')
            if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'testing') {
                console.log('Images resized and going back');
                res.status(200).json({'location': '/imageserving/uploads/' + year + '/' + month + '/' + name + '.' + extension, fileIndex: '1'});
            }
            else if (process.env.NODE_ENV === 'production') {
                //possibly use req.hostname
                res.status(200).json({'location': 'mysite/uploads/' + year + '/' + month + '/' + name + '.' + extension, fileIndex: '1'});
            }   
        })

标签: node.jsimageapacheimage-processingsharp

解决方案


尝试更新这一行:

sharp(folderName + name + '.' + extension)

对此:

return sharp(folderName + name + '.' + extension)

...这应该确保以下then()部分正确链接到承诺,并避免可能导致不一致行为的潜在竞争条件。


推荐阅读