【问题标题】:Access uploaded image in Sails.js backend project在 Sails.js 后端项目中访问上传的图像
【发布时间】:2015-09-20 00:41:12
【问题描述】:

我正在尝试上传,然后访问图像。上传进展顺利,将图像上传到资产/图像,但是当我尝试从浏览器访问图像时,如http://localhost:1337/images/image-name.jpg 它给了我 404。我将 Sails.js 仅用于后端目的 - 用于 API,项目是使用 --no-front-end 选项创建。我的前端在 AngularJS 上。

我的上传功能:

avatarUpload: function(req, res) {
    req.file('avatar').upload({
        // don't allow the total upload size to exceed ~10MB
        maxBytes: 10000000,
        dirname: '../../assets/images'
    }, function whenDone(err, uploadedFiles) {
        console.log(uploadedFiles);
        if (err) {

            return res.negotiate(err);
        }

        // If no files were uploaded, respond with an error.
        if (uploadedFiles.length === 0) {

            return res.badRequest('No file was uploaded');
        }

        // Save the "fd" and the url where the avatar for a user can be accessed
        User
            .update(req.userId, {

                // Generate a unique URL where the avatar can be downloaded.
                avatarUrl: require('util').format('%s/user/avatar/%s', sails.getBaseUrl(), req.userId),

                // Grab the first file and use it's `fd` (file descriptor)
                avatarFd: uploadedFiles[0].fd
            })
            .exec(function (err){
                if (err) return res.negotiate(err);
                return res.ok();
            });
    });
}

我在 assets/images 文件夹中看到图像 - 类似这样 - 54cd1fc5-89e8-477d-84e4-dd5fd048abc0.jpg

http://localhost:1337/assets/images/54cd1fc5-89e8-477d-84e4-dd5fd048abc0.jpg - 给出 404

http://localhost:1337/images/54cd1fc5-89e8-477d-84e4-dd5fd048abc0.jpg - 给出 404

【问题讨论】:

    标签: node.js http-status-code-404 sails.js assets image-uploading


    【解决方案1】:

    发生这种情况是因为您的应用程序访问的资源不是直接从assets 目录访问的,而是从项目根目录中的.tmp 目录访问的。

    升起风帆时,资产将复制到 .tmp 目录,因此在升起之后添加的任何内容都不会出现在 .tmp 中。

    我通常做的是将文件上传到.tmpcopy 完成后到assets。这样assets 就不会被污染,以防上传失败。

    让我们知道这是否有效。祝你好运!

    更新 为此找到了相关的link

    【讨论】:

    • 非常感谢。我设法按照您提供的教程进行上传并访问图片。它真的帮助了我。需要注意的一件小事 - 将上传的文件从 assets 复制到 .tmp 文件夹时,如果文件夹结构 - .tmp/public/images/uploads 不存在,我们需要先创建它,否则 fs 错误会中断应用程序,如果没有被捕获.
    • 确实!如果文件夹不存在,您可以使用 mkdirp 模块或 fs-extra(用于添加功能)使用单个命令创建文件夹。或者只是使用这个well-reasoned solution
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2017-05-14
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    相关资源
    最近更新 更多