后端代码
//https://portal.qiniu.com/user/key var accessKey = '-xxx-QvPiZzXYWY9AuytTjgix'; var secretKey = '-xxx'; var mac = new qiniu.auth.digest.Mac(accessKey, secretKey); var options = { scope: "xxx" //存储空间的名字,创建的存储空间的时候,自己取的名字 }; var putPolicy = new qiniu.rs.PutPolicy(options); var uploadToken=putPolicy.uploadToken(mac); router.get('/qiniu', function(req, res, next) { res.json({ putPolicy:putPolicy, uploadToken:uploadToken }) });
其中,accessKey 和 secretKey 在 https://portal.qiniu.com/user/key页面查看
前端代码:
<input type="file" name="files" id="files" value="" />
$("#files").change(function(){ var me = this; $.ajax({ type:"get", url:"http://127.0.0.1:3000/qiniu", }).then(function(ret){ var formData = new FormData(); // 构建表单数据 formData.append('token', ret['uploadToken']); // 设置accessid // formData.append('file', me.files[0]); // 设置文件 upload(formData) }).fail(function(f){ console.log("f") }); }); function upload(formData){ //http(s)://upload.qiniup.com $.ajax({ url: 'http://up-z2.qiniup.com', type: 'post', data: formData, contentType: false, processData: false, success: function (res) { console.info(res); }, error: function (error) { console.info(error); } }) }
上传成功后返回了文件的名称,不在是原来的名称
参考文档:https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md