在Sails.js后端项目中访问上传的图像

Hri*_*nev 5 assets image-uploading node.js http-status-code-404 sails.js

我正在尝试上传然后访问图像.上传进展顺利,将图片上传到资源/图片,但是当我尝试从浏览器访问图像时,如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();
            });
    });
}
Run Code Online (Sandbox Code Playgroud)

我在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

gal*_*pse 5

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

.tmp当风帆被抬起时,资产被复制到目录中,因此在升降机之后添加的任何东西都不存在.tmp.

我最常做的是上传.tmp复制该文件assets上完成.assets如果上传因任何原因失败,这种方式不会受到污染.

如果有效,请告诉我们.祝好运!

更新 找到相关链接.