Sails.js上传图片不起作用

时间:2017-12-20 15:05:15

标签: javascript node.js sails.js

我正在尝试上传图片并将图片名称输入MySQL。但我仍然坚持上传图片。我总是得到结果“文件上传成功”

这是控制器。

upload: function(req, res){
    var picture_path = req.param('picture_path');

    req.file('image').upload({maxBytes: 1000000, dirname : '/assets/pic_items'},function whenDone(err, uploadedFiled){
        if (err) {
            return res.negotiate(err);
        }   
            console.log(uploadedFiled);
            return res.json({
                message: uploadedFiled.length + ' files(s) uploaded successfully'
            });
        if (uploadedFiled.length === 0){
            return res.badRequest('no file was uploaded');
        }
    });
},

1 个答案:

答案 0 :(得分:1)

要回答你的问题,我会假设一些事情。

  1. 您已成功将MySQL连接添加到配置目录中的connections.js文件中。
  2. 您已经生成了一个名为' gallery'的模型和控制器,它代表了您的MySQL数据库中的一个表,也称为“#”;#39;并且您的模型已成功创建为此表中字段的表示。
  3. 在图库表/模型中,您有一个名为' image_name'的字段。存储图像的名称以及名为' image_uid'的字段。它将存储唯一标识符(文件描述符)。
  4. 所以现在你应该有一个看起来像这样的Gallery模型:

    /**
     * Gallery.js
     *
     * @description :: TODO: You might write a short summary of how this model works and what it represents here.
     * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
     */
    
    module.exports = {
    
      attributes: {
        // Anything else you want to capture in your DB
        image_name : {
          type : 'string'
        },
    
        image_uid : {
          type: 'string'
        },
      }
    };
    

    在GalleryController中,创建上传功能/路线以处理图像上传和数据库插入。这应该是:

    upload: function(req, res, next) {
        var params = req.params.all();
        console.log(params);
    
        req.file('fileToUpload').upload({
            // don't allow the total upload size to exceed ~10MB
            dirname: '../../assets/images/gallery',
            maxBytes: 10000000
        },function (err, uploadedFile) {
            if (err) {
                return res.serverError(err); 
            }
    
            // If no files were uploaded, respond with an error.
            if (uploadedFile.length === 0){
                return res.serverError("No files were uploaded!"); 
            }
    
            // Use this log all the uploaded file info
            // console.log(uploadedFile[0]);
    
            // Get the name of the file
            var fileName = uploadedFile[0].filename;
            // Get the file descriptor and remove the directory details
            var fileUID = uploadedFile[0].fd.replace(/^.*[\\\/]/, '');
    
            // Create a galleryItem to insert into database
            var galleryItem = {};
            galleryItem.image_name = fileName;
            galleryItem.image_uid = fileUID;
    
            // Create the image in your Database
            Gallery.create(galleryItem, function (err, gallery) {
                if(err) {
                    return res.serverError('An error occured while adding Image in the DB');
                }
    
                // return whatever or wherever you want
                return res.redirect("/gallery/");
            });
        });
    },
    

    最后,在客户端上,您应确保表单捕获使用多部分编码,输入名称与' req.file(" fileToUpload")相匹配。控制器中的参数。这是一个非常基本的例子:

    <form action="/gallery/upload" method="post" enctype="multipart/form-data">
      <input type="file" name="fileToUpload" id="fileToUpload">
      <input type="submit" value="Upload Image" name="submit">
    </form>
    

    显示图像就像从数据库中读取图库项目并将image_uid传递给图像标记一样简单。

    <img src="/images/gallery/<%= gallery.image_uid %>" alt="<%= gallery.image_name %>" >