thinkjs与Fine Uploader的邂逅
/**
* controller
* @return
*/
module.exports = Controller("Home/BaseController", function(){
"use strict";
return {
indexAction: function(){
this.display();
},
uploadFileAction: function() {
var self = this;
var fileInfo = this.file('qqfile');
//http://www.thinkjs.org/doc/http.html#上传的文件
/*
//fileInfo的值
{
fieldName: 'qqfile',
originalFilename: '1.jpg',
path: '/home/maoshuai/htdocs/mtyras/App/Runtime/Temp/23886-1c2xozp.jpg',
headers:
{ 'content-disposition': 'form-data; name="qqfile"; filename="1.jpg"',
'content-type': 'image/jpeg' },
ws:
{ _writableState:
{ highWaterMark: 16384,
objectMode: false,
needDrain: false,
ending: true,
ended: true,
finished: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
sync: false,
bufferProcessing: false,
onwrite: [Function],
writecb: null,
writelen: 0,
buffer: [],
errorEmitted: false },
writable: true,
domain: null,
_events: { error: [Object], close: [Object] },
_maxListeners: 10,
path: '/home/maoshuai/htdocs/mtyras/App/Runtime/Temp/23886-1c2xozp.jpg',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 28618,
closed: true },
size: 28618
}*/
if(fileInfo) {
self.json({
error: 0,
errmsg: 'ok',
success: true //只有success返回true才认为上传成功
});
}else {
self.error();
}
}
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="http://s7.qhimg.com/!f33a50ea/fine-uploader.css">
<title>Fine Uploader与thinkjs的邂逅</title>
</head>
<body>
<div id="fine-uploader-wrapper">
<div class="qq-uploader-selector qq-uploader">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span>拖拽上传区域</span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>选择文件</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>上传进度</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list">
<li>
<div class="qq-progress-bar-container-selector">
<div class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<span class="qq-edit-filename-icon-selector qq-edit-filename-icon"></span>
<span class="qq-upload-file-selector qq-upload-file"></span>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<span class="qq-upload-size-selector qq-upload-size"></span>
<a class="qq-upload-cancel-selector qq-upload-cancel" href="#">取消</a>
<a class="qq-upload-retry-selector qq-upload-retry" href="#">重试</a>
<a class="qq-upload-delete-selector qq-upload-delete" href="#">删除</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</div>
<button id="upload-btn">上传按钮</button>
<script type="text/javascript" src="http://s8.qhimg.com/!240a7702/fine-uploader.js"></script>
<script type="text/javascript">
//具体参数参考源码qq.FineUploaderBasic中的_options查看
var uploader = new qq.FineUploader({
element: document.getElementById("fine-uploader-wrapper"), //上传按钮
request: {
endpoint: 'test/uploadFile' //上传接口地址
},
multiple: false, //是否多个文件
autoUpload: false, //是否支持上传
validation: {
allowedExtensions: ['jpeg', 'jpg', 'png'], //上传文件约束条件
sizeLimit: 2048000 //bytes 2000KB
},
callbacks: {
onSubmit: function(id, fileName) {
//文件开始提交
console.log(fileName,'文件开始提交');
},
onUpload: function(id, fileName) {
//文件开始上传
console.log(fileName,'文件开始提交');
},
onProgress: function(id, fileName, loaded, total) {
//文件正在上传
console.log(fileName,'已上传'+(loaded/total)*100+'%');
},
onComplete: function(id, fileName, responseJSON) {
//文件上传成功
console.log(fileName,'上传成功,返回信息为:',responseJSON);
},
onCancel: function(id, fileName) {
//取消文件上传
console.log('取消',fileName,'上传');
}
},
messages: {
noFilesError: '没有选中文件'
},
text: {
formatProgress: "{percent}% of {total_size}",
failUpload: "上传失败",
waitingForResponse: "上传中...",
paused: "暂停"
},
template: 'fine-uploader-wrapper', //ID
debug: true
}); document.getElementById('upload-btn').onclick = function() {
uploader.uploadStoredFiles();
}
</script>
</body>
</html>
$(dom).fineUploader(conf);
new qq.FineUploader(conf);
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
endpoint: "/server/upload",
params: {},
paramsInBody: true,
customHeaders: {},
forceMultipart: true,
inputName: "qqfile",
uuidName: "qquuid",
totalFileSizeName: "qqtotalfilesize",
filenameParam: "qqfilename"
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null,
image: {
maxHeight: 0,
maxWidth: 0,
minHeight: 0,
minWidth: 0
}
},
callbacks: {
onSubmit: function(id, name) {},
onSubmitted: function(id, name) {},
onComplete: function(id, name, responseJSON, maybeXhr) {},
onAllComplete: function(successful, failed) {},
onCancel: function(id, name) {},
onUpload: function(id, name) {},
onUploadChunk: function(id, name, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
onResume: function(id, fileName, chunkData) {},
onProgress: function(id, name, loaded, total) {},
onTotalProgress: function(loaded, total) {},
onError: function(id, name, reason, maybeXhrOrXdr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {},
onSessionRequestComplete: function(response, success, xhrOrXdr) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
maxHeightImageError: "Image is too tall.",
maxWidthImageError: "Image is too wide.",
minHeightImageError: "Image is not tall enough.",
minWidthImageError: "Image is not wide enough.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: "preventRetry"
},
classes: {
buttonHover: "qq-upload-button-hover",
buttonFocus: "qq-upload-button-focus"
},
chunking: {
enabled: false,
concurrent: {
enabled: false
},
mandatory: false,
paramNames: {
partIndex: "qqpartindex",
partByteOffset: "qqpartbyteoffset",
chunkSize: "qqchunksize",
totalFileSize: "qqtotalfilesize",
totalParts: "qqtotalparts"
},
partSize: 2000000,
// only relevant for traditional endpoints, only required when concurrent.enabled === true
success: {
endpoint: null
}
},
resume: {
enabled: false,
recordsExpireIn: 7, //days
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
if (fileOrBlobName !== undefined && fileOrBlobName.length > 33) {
fileOrBlobName = fileOrBlobName.slice(0, 19) + "..." + fileOrBlobName.slice(-14);
}
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"]
},
deleteFile: {
enabled: false,
method: "DELETE",
endpoint: "/server/upload",
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false,
allowXdr: false
},
blobs: {
defaultName: "misc_data"
},
paste: {
targetElement: null,
defaultName: "pasted_image"
},
camera: {
ios: false,
// if ios is true: button is null means target the default button, otherwise target the button specified
button: null
},
// This refers to additional upload buttons to be handled by Fine Uploader.
// Each element is an object, containing `element` as the only required
// property. The `element` must be a container that will ultimately
// contain an invisible `<input type="file">` created by Fine Uploader.
// Optional properties of each object include `multiple`, `validation`,
// and `folders`.
extraButtons: [],
// Depends on the session module. Used to query the server for an initial file list
// during initialization and optionally after a `reset`.
session: {
endpoint: null,
params: {},
customHeaders: {},
refreshOnReset: true
},
// Send parameters associated with an existing form along with the files
form: {
// Element ID, HTMLElement, or null
element: "qq-form",
// Overrides the base `autoUpload`, unless `element` is null.
autoUpload: false,
// true = upload files on form submission (and squelch submit event)
interceptSubmit: true
},
// scale images client side, upload a new file for each scaled version
scaling: {
// send the original file as well
sendOriginal: true,
// fox orientation for scaled images
orient: true,
// If null, scaled image type will match reference image type. This value will be referred to
// for any size record that does not specific a type.
defaultType: null,
defaultQuality: 80,
failureText: "Failed to scale",
includeExif: false,
// metadata about each requested scaled version
sizes: []
},
workarounds: {
iosEmptyVideos: true,
ios8SafariUploads: true,
ios8BrowserCrash: true
}
};
- multiple是否支持多文件上传
- autoUpload是否自动上传,就是说选中文件后,是否还需要手动点击上传按钮触发开始上传事件
- validation文件约束条件,包含文件格式、文件最大值、文件最小值
- callbacks各种回调函数,包含开始提交、开始上传、正在上传、上传成功、取消上传
- messages一些默认提示信息,可以将源文件的错误提示汉化调整,例子中只是i调整了noFilesError,业务可以根据自己需求进行配置
- template可以使用script模版或者dom模版,只要传模版的ID字符串或者dom对象
- debug这个就不用说了,为了开发调试使用,会记录详细的上传过程,便于查找问题出现的位置
thinkjs与Fine Uploader的邂逅的更多相关文章
- Fine Uploader文件上传组件
最近在处理后台数据时需要实现文件上传.考虑到对浏览器适配上采用Fine Uploader. Fine Uploader 采用ajax方式实现对文件上传.同时在浏览器中直接支持文件拖拽[对浏览器版本有要 ...
- [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传
原文 [代码示例]用Fine Uploader+ASP.NET MVC实现ajax文件上传 Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件 ...
- 用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]
Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件的 Javascript 组件. This project attempts to achi ...
- Fine Uploader 简单配置方法
由于jquery.uploadify是基于flash的jquery上传控件,客户老是说出问题,所以今天换成了一个纯js的异步上传控件. 这方面的资料很少,故此记下来分享一下. 项目地址:Fine Up ...
- web文件上传组件比较jQuery File Upload和Fine Uploader
jQuery File Upload: https://blueimp.github.io/jQuery-File-Upload/ Fine Uploader: http://fineuploader ...
- [Fine Uploader] 用Fine Uploader+ASP.NET MVC实现ajax文件上传[代码示例]
Fine Uploader(http://fineuploader.com/)是一个实现 ajax 上传文件的 Javascript 组件 This project attempts to ach ...
- 上传组件Fine Uploader在ASP.NET中的应用
现如今,世面上流行着许多前端上传组件,例如:Uploadify(http://www.uploadify.com/),Fine Uploader,等等.这篇博客从头开始,介绍如何在ASP.NET MV ...
- Fine Uploader + Spring3.2.2(Java+html5上传) SpringMVC+jquery-fineuploader 文件上传
需求:要实现多文件上传,且要支持手机等移动设备... springmvc文件上传真头疼,网上搜了半天没发现都是TMD的用submit按钮提交到后台的,就没有插件的吗?最后发现了fineUploader ...
- GitHub托管BootStrap资源汇总(持续更新中…)
Twitter BootStrap已经火过大江南北,对于无法依赖美工的程序员来说,这一成熟前卫的前端框架简直就一神器,轻轻松松地实现出专业的UI效果.GitHub上相关的的开源项目更是层出不穷,在此整 ...
随机推荐
- thinkphp连接mysql5.5版本数据库
//数据库配置信息 'DB_TYPE' => 'mysqli', // 数据库类型 'DB_HOST' => 'localhost', // 服务器地址 'DB_NAME' => ' ...
- MySQL精粹
关于Mysql整理的需要记忆和熟练掌握的内容 1.查询数据表的信息(比如有多少行数据): show table status like 'tab_User' -- 数据表中的数量 2. 使用 ex ...
- C语言--返回局部变量的地址
我们可能会经常写出这样的代码: int add(int a , int b) { return a + b; } 当然,这是合理的写法,使函数的返回值为 int ,所以,调用函数后会返回一个i ...
- Operation System - Peterson's Solution算法 解决多线程冲突
Person's solution 是用来一种基于软件的解决关键区域问题的算法(critical-section). 它并不是完美的,有可能不对地工作.并且是限制解决两个进程同步的问题. 可是它非常e ...
- ViewPager顶部标题控件PagerSlidingTabStrip
最近搞一个项目,要求做一个和网易新闻顶部菜单的滑动效果,如图: 顶部标题中下面有个红色的矩形小条,左右滑动时会跟随手势动态滑动,效果很绚丽,唉,特效啊! 自己搞了一上午无果,还是是github上找大神 ...
- 在线C语言编译器/解释器
在线C语言编译器/解释器 本文介绍两个C语言在线解释器/编译器,这些工具可以提高代码片段检测方便的工作效率,并可以保证这些代码的正确性,而且还可以和别人一起编辑/分享之间的代码,这样可以共同分析代码并 ...
- HTML与CSS入门——第八章 使用外部和内部链接
知识点: 1.链接锚的使用方法 2.在自己的网站上的页面之间链接的方法 3.链接到外部内容的方法 4.链接到一个E-mail地址的方法 5.在新浏览器窗口中查看链接的方法 6.用CSS为链接添加样式的 ...
- VS2015 新Web项目(C#6)出现CS1617异常的解决
VS2015 新Web项目(C#6)出现CS1617错误的解决 VS2015新增了对C#6的支持. 在新的Web项目模板中通过引入nuget包Microsoft.CodeDom.Providers.D ...
- js+图片实现图片flash效果
var pic_width=685; //图片宽度 var pic_height=225; // 图片高度 var button_pos=4; //按扭位置 1左 2右 3上 4下 var stop_ ...
- (转)CSS 禁止浏览器滚动条的方法
1.完全隐藏 在里加入scroll="no",可隐藏滚动条: 这个我用的时候完全没效果,不知道是什么原因!不过好多人说这么用可以,大概是用的位置不一样吧 2.在不需要时隐 ...