关于element上传到七牛云出现500错误到问题

我的需求就是前端提交图片之后,自动上传到七牛云中。

前端提交图片之后出现500错误,请问一下到底哪里出错了。

后端

const router = require('express').Router();
const qiniu = require('qiniu');

qiniu.conf.ACCESS_KEY = 'you key';
qiniu.conf.SECRET_KEY = 'you key';

router.post('/upload', (req,res) => {

    const uptoken = (bucket,key) => {
        let putPolicy = new qiniu.rs.PutPolicy(bucket + ':' + key);
        return putPolicy.token();
    }

    const uploadFile = (uptoken,key,localfile) => {
        qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
          if(!err) {
            // 上传成功, 处理返回值
            return res.json({
                hash: ret.hash,
                key: ret.key,
                per: ret.persistentId
            });
          } else {
            // 上传失败, 处理返回代码
            console.log(err);
          }
        });        
    }

    const bucket = 'image';

    const key = req.body.key;

    const token = uptoken(bucket,key,req.files[0].path)

    uploadFile(token,key,req.files[index].path)
})

module.exports = router;

index.html

<body>
    <div id="app">
      <el-upload
          action="https://upload.qbox.me"
          :data="dataObj"
          drag
          :multiple="true"
          :before-upload="beforeUpload"
          :on-success='handleSuccess'>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
      </el-upload>
    </div>
 </body>
    <script>
    new Vue({
        el: '#app',
        data:{
            dataObj: { token: '', key: '' },
            image_uri: [],
            fileList: []
        },
        methods:{
            beforeUpload(file) {
                const tath = this;
                const name = file.name;
                const curr = Date.now().toString();
                const key = encodeURI(`${curr}_${name}`);
                return new Promise((resolve,reject) => {
                    axios.post('/api/qiniu/upload',{ key }).then(res => {
                        consoel.log(res.data);
                        that.data.dataObj.token = res.data.token;
                        tath.data.dataObj.key = res.data.key;
                        resolve(true);
                    }).catch(err => {
                        console.log(err);
                        reject(false);
                    })
                });

            },
            handleSuccess() {
                console.log('上传成功')
            }
        }
    })
    </script>
阅读 4.2k
1 个回答

500是后台程序有问题,没看到你后台怎么接受前端传的文件,我之前是先用 multiparty 处理了一下,可以给你参考下。

"use strict";

const qiniu = require('qiniu');//七牛云API
const multiparty = require('multiparty');//文件上传中间件
const fs = require('fs');
const path = require('path');

const qiniuConfig = require('../config/qiniuConfig.js');//七牛云相关配置文件

module.exports = {

    /*
    *  图片上传功能:文件上传的一种,先将图片保存到本文件夹的/public/images目录下,随后上传至七牛云
    *         输入:Content-Type:multipart/form-data, key:file,value:图片资源
    *         返回:图片的url地址
    */
    /**
     * @api {post} /upload/image 图片上传
     * @apiName uploadImage
     * @apiGroup uploadImage
     *
     * @apiParam {file} file 图片文件
     *
     * @apiSuccess {String} url 图片url地址
     */
    upload_image: (req, res) => {
        console.log('----upload from frontEnd---');
        console.log('request headers: ', req.headers);
        //生成multiparty对象,并配置上传路径
        let form = new multiparty.Form({
            uploadDir: './public/images',
            encoding: 'utf-8',
            // maxFilesSize: 2 * 1024 * 1024,//默认2M大小限制
        });
        //上传文件
        form.parse(req, (err, fields, files) => {
            if(err){
                console.log(err);
            }else {
                console.log('--uploaded to backEnd--');

                console.log('files: ',files);
                console.log('file: ',files.file[0]);
                console.log('file path: ',files.file[0].path);
                console.log('random file name:',path.basename(files.file[0].path));

                //调用七牛云上传函数,传入文件路径和随机文件名
                qiniu_upload(files.file[0].path, path.basename(files.file[0].path),res);
            }
        });

        /*七牛云上传:输入文件路径和文件名称*/
        function qiniu_upload(path, name, res) {
            console.log('---qiniu---');
            //需要填写自己的 Access Key 和 Secret Key
            qiniu.conf.ACCESS_KEY = qiniuConfig.access_key;
            qiniu.conf.SECRET_KEY = qiniuConfig.secret_key;

            let bucket = qiniuConfig.bucket;//要上传的空间
            let key = name;//上传到七牛后保存的文件名

            //构建上传策略函数
            function uptoken(bucket, key) {
                let putPolicy = new qiniu.rs.PutPolicy(bucket+':'+key);
                return putPolicy.token();
            }

            let token = uptoken(bucket, key);//生成上传 Token
            
            // 测试 filePath = './public/images/1.png';
            const filePath = path;//要上传文件的本地路径

            //构造上传函数
            function uploadFile(uptoken, key, localFile) {
                let extra = new qiniu.io.PutExtra();
                qiniu.io.putFile(uptoken, key, localFile, extra, (err, ret) => {
                    if(!err) {
                        // 上传成功, 处理返回值
                        console.log(ret.hash, ret.key, ret.persistentId);
                    } else {
                        // 上传失败, 处理返回代码
                        console.log(err);
                        res.send('upload error');
                    }
                });
            }

            //调用uploadFile上传
            uploadFile(token, key, filePath);
            let urlPic = qiniuConfig.urlPre + key;
            console.log('urlPic: ',urlPic);
            res.send(urlPic);
        }
    }
};
推荐问题
logo
七牛云问答
子站问答
访问
宣传栏