Skip to content

add formdata demo and modify readme.md #206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
bower_components
demo/config.js
demo/deploy.sh
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ Qiniu-JavaScript-SDK

Qiniu-JavaScript-SDK (下文简称为 JS-SDK)适用于 IE8+、Chrome、Firefox、Safari 等浏览器,基于七牛云存储官方 API 构建,其中上传功能基于 [Plupload](http://www.plupload.com/) 插件封装。开发者基于 JS-SDK 可以方便的从浏览器端上传文件至七牛云存储,并对上传成功后的图片进行丰富的数据处理操作。

不考虑兼容性的情况下,如手机端,建议直接使用 Formdata 结合七牛[表单上传](https://developer.qiniu.com/kodo/manual/form-upload)的方式上传文件。

[ Formdata 上传 demo ](http://jssdk.demo.qiniu.io/formdata)

![ Formdata ](http://oky1vwhqm.bkt.clouddn.com/1486368013.png)

Qiniu-JavaScript-SDK 为客户端 SDK,没有包含 token 生成实现,为了安全,token 建议通过网络从服务端获取,具体生成代码可以参考以下服务端 SDK 的文档。

- [Java](http://developer.qiniu.com/code/v7/sdk/android.html)
Expand Down Expand Up @@ -190,7 +196,7 @@ Qiniu-JavaScript-SDK 的示例 Demo 中的服务器端部分是基于[ Node.js
// Ajax请求downToken的Url,私有空间时使用,JS-SDK 将向该地址POST文件的key和domain,服务端返回的JSON必须包含`url`字段,`url`值为该文件的下载地址
// unique_names: true, // 默认 false,key 为文件名。若开启该选项,JS-SDK 会为每个文件自动生成key(文件名)
// save_key: true, // 默认 false。若在服务端生成 uptoken 的上传策略中指定了 `sava_key`,则开启,SDK在前端将不对key进行任何处理
domain: '<Your bucket domain>', // bucket 域名,下载资源时用到,**必需**
domain: '<Your bucket domain>', // bucket 域名,下载资源时用到,如:'http://xxx.bkt.clouddn.com/' **必需**
container: 'container', // 上传区域 DOM ID,默认是 browser_button 的父元素,
max_file_size: '100mb', // 最大文件体积限制
flash_swf_url: 'path/of/plupload/Moxie.swf', //引入 flash,相对路径
Expand Down Expand Up @@ -449,7 +455,7 @@ Qiniu-JavaScript-SDK 的示例 Demo 中的服务器端部分是基于[ Node.js
<a id="demo"></a>
### 运行示例

1. 进入项目根目录,执行 `make install` 安装依赖第三方库
1. 进入项目根目录,执行 `make install` 或 `npm install & bower install` 安装依赖第三方库
2. 进入 `demo` 目录,按照目录下的 `config.example` 示例,创建 `config.js` 文件,其中,`Access Key` 和 `Secret Key` 按如下方式获取

* [开通七牛开发者帐号](https://portal.qiniu.com/signup)
Expand All @@ -463,11 +469,11 @@ Qiniu-JavaScript-SDK 的示例 Demo 中的服务器端部分是基于[ Node.js
'Bucket_Name': '<Your Bucket Name>',
'Port': 19110,
'Uptoken_Url': '<Your Uptoken_Url>', // demo 启动后会在本地 /uptoken 上提供获取 uptoken 的接口,所以这里可以填 'uptoken'
'Domain': '<Your Bucket Domain>'
'Domain': '<Your Bucket Domain>' // Bucket 的外链默认域名,在 Bucket 的内容管理里查看,如:'http://xxx.bkt.clouddn.com/'
}

```
3. 进入项目根目录,执行 `make dev` 访问 `http://127.0.0.1:19110/` 或 `http://localhost:19110/`
3. 进入项目根目录,执行 `make dev` 或 `node demo/server.js` 访问命令行打印出的 demo 地址。

<a id="note"></a>
### 说明
Expand Down
4 changes: 2 additions & 2 deletions demo/config.js.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module.exports = {
'ACCESS_KEY': '<Your Access Key>',
'ACCESS_KEY': '<Your Access Key>', // https://portal.qiniu.com/user/key
'SECRET_KEY': '<Your Secret Key>',
'Bucket_Name': '<Your Bucket Name>',
'Port': 19110,
'Uptoken_Url': 'uptoken',
'Domain': 'http://qiniu-plupload.qiniudn.com/'
'Domain': '<Your Bucket Name>' // bucket domain eg:http://qiniu-plupload.qiniudn.com/
};
57 changes: 57 additions & 0 deletions demo/scripts/formdata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// jQuery zepto vue angular 等库皆有 progress 的实现 以jQuery为例:
$(function(){
var $key = $('#key'); // file name eg: the file is image.jpg,but $key='a.jpg', you will upload the file named 'a.jpg'
var $userfile = $('#userfile'); // the file you selected

// upload info
var $selectedFile = $('.selected-file');
var $progress = $(".progress");
var $uploadedResult = $('.uploaded-result');

$("#userfile").change(function() { // you can ues 'onchange' here to uplpad automatically after select a file
$uploadedResult.html('');
var selectedFile = $userfile.val();
if (selectedFile) {
// randomly generate the final file name
var ramdomName = Math.random().toString(36).substr(2) + $userfile.val().match(/\.?[^.\/]+$/);
$key.val(ramdomName);
$selectedFile.html('文件:' + selectedFile);
} else {
return false;
}
var f = new FormData(document.getElementById("testform"));
$.ajax({
url: 'http://upload.qiniu.com/', // Different bucket zone has different upload url, you can get right url by the browser error massage when uploading a file with wrong upload url.
type: 'POST',
data: f,
processData: false,
contentType: false,
xhr: function(){
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',function(e) {
// console.log(e);
if (e.lengthComputable) {
var percent = e.loaded/e.total*100;
$progress.html('上传:' + e.loaded + "/" + e.total+" bytes. " + percent.toFixed(2) + "%");
}
}, false);
}
return myXhr;
},
success: function(res) {
console.log("成功:" + JSON.stringify(res));
var str = '<span>已上传:' + res.key + '</span>';
if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
str += '<img src="' + domain + res.key + '"/>';
}
$uploadedResult.html(str);
},
error: function(res) {
console.log("失败:" + JSON.stringify(res));
$uploadedResult.html('上传失败:' + res.responseText);
}
});
return false;
});
});
15 changes: 14 additions & 1 deletion demo/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,25 @@ app.get('/multiple', function(req, res) {
});
});

app.get('/formdata', function(req, res) {
var token = uptoken.token();
res.render('formdata.html', {
domain: config.Domain,
uptoken: token
});
});

qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);


app.listen(config.Port, function() {
console.log('Listening on port %d', config.Port);
console.log('Listening on port %d\n', config.Port);
console.log('▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ Demos ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽ ▽')
console.log(' ▹▹▹▹▹▹▹▹▹▹▹▹▹▹▹▹ Upload: http://127.0.0.1:%d ◁ ◁ ◁ ◁ ◁ ◁ ◁', config.Port);
console.log(' ▹▹▹▹▹▹▹ Multiple upload: http://127.0.0.1:%d/multiple ◁ ◁ ◁', config.Port);
console.log(' ▹▹▹▹▹▹▹ Formdata upload: http://127.0.0.1:%d/formdata ◁ ◁ ◁', config.Port);
console.log('△ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △ △\n');
});
79 changes: 79 additions & 0 deletions demo/styles/formdata.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#testform{
display: none;
}
body{
padding: 0;
margin:0;
font-family: Tahoma,Arial,Roboto,"Droid Sans","Helvetica Neue","Droid Sans Fallback","Heiti SC",sans-self;
color: #666;
}
.title{
background-color: #0983C7;
line-height: 40px;
text-align: center;
color:#fff;
font-family: '微软雅黑';
}
.container{
width: 100%;
margin:0 auto;
max-width:640px;
background-color: #fff;
border-radius: 10px;
min-height: 600px;
}
label{
display:block;
width: 300px;
height:150px;
margin: 30px auto;
border-radius: 10px;
border:2px dashed #ddd;
overflow: hidden;
cursor: pointer;
}
label span{
display:block;
width:50px;
height:50px;
border-radius: 100%;
border:3px solid #0983C7;
margin:30px auto 15px;
position:relative;
}
label em{
font-style: normal;
text-align: center;
display:block;
}
label span:before, label span:after{
display:block;
content:'';
background-color: #0983C7;
position: absolute;
}
label span:before{
width:3px;
height:30px;
top:10px;
left:24px;
}
label span:after{
width:30px;
height:3px;
top:24px;
left:10px;
}
.selected-file, .progress, .uploaded-result{
line-height: 30px;
margin: 0 20px;
}
.uploaded-result span{
display: block;
}
.uploaded-result img{
display:block;
margin: 20px auto;
width:100%;
max-width: 100%;
}
45 changes: 45 additions & 0 deletions demo/views/formdata.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>formdata 上传 demo</title>
<link rel="stylesheet" href="../styles/formdata.css">
<script src="../../bower_components/jquery/jquery.min.js"></script>
<script src="../scripts/formdata.js"></script>
<script>
var domain = "<%= domain %>"; // you bucket domain eg: http://xxx.bkt.clouddn.com
</script>
</head>
<body>
<div class="container">
<div class="title">Formdata 上传 demo</div>

<!-- Document:https://developer.qiniu.com/kodo/manual/form-upload -->
<form id="testform" method="post" enctype="multipart/form-data">
<input name="key" id="key" type="hidden" value="">
<input name="token" type="hidden" value="<%= uptoken %>">
<input id="userfile" name="file" type="file" />

<!-- take photo with phone -->
<!-- <input id="userfile" name="file" accept="image/*" type="file" /> -->

<!-- take video with phone -->
<!-- <input id="userfile" name="file" type="file" accept="video/*"/> -->

<input name="accept" type="hidden" />
</form>

<!-- add file -->
<label for="userfile">
<span></span>
<em>添加文件</em>
</label>

<!-- upload info -->
<div class="selected-file"></div>
<div class="progress"></div>
<div class="uploaded-result"></div>
</div>
</body>
</html>
18 changes: 11 additions & 7 deletions dist/qiniu.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/*!
* qiniu-js-sdk v1.0.17.1
* qiniu-js-sdk v1.0.18
*
* Copyright 2015 by Qiniu
* Released under GPL V2 License.
*
* GitHub: http://github.com/qiniu/js-sdk
*
* Date: 2016-10-13
* Date: 2017-2-6
*/

/*global plupload ,mOxie*/
Expand Down Expand Up @@ -1335,7 +1335,8 @@ function QiniuJsSDK() {
status: ajax.status,
response: ajax.responseText,
file: file,
code: -200
code: -200,
responseHeaders: ajax.getAllResponseHeaders()
};
logger.debug("mkfile is error: ", info);
uploader.trigger('Error', info);
Expand Down Expand Up @@ -1392,14 +1393,17 @@ function QiniuJsSDK() {
* @return {String} url of processed image
*/
this.imageView2 = function(op, key) {
var mode = op.mode || '',

if (!/^\d$/.test(op.mode)) {
return false;
}

var mode = op.mode,
w = op.w || '',
h = op.h || '',
q = op.q || '',
format = op.format || '';
if (!mode) {
return false;
}

if (!w && !h) {
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions dist/qiniu.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/qiniu.min.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "qiniu-js",
"jsName": "qiniu",
"version": "1.0.17.1",
"version": "1.0.18",
"private": false,
"scripts": {
"start": "node demo/server.js"
Expand Down
11 changes: 7 additions & 4 deletions src/qiniu.js
Original file line number Diff line number Diff line change
Expand Up @@ -1393,14 +1393,17 @@ function QiniuJsSDK() {
* @return {String} url of processed image
*/
this.imageView2 = function(op, key) {
var mode = op.mode || '',

if (!/^\d$/.test(op.mode)) {
return false;
}

var mode = op.mode,
w = op.w || '',
h = op.h || '',
q = op.q || '',
format = op.format || '';
if (!mode) {
return false;
}

if (!w && !h) {
return false;
}
Expand Down