‘壹’ WebUploader踩坑
采坑点:
1、uploader.removeFile(fileid, true):删除文件时需要带上第二个参数true,才代表从队列移除;
2、uploader.getFiles('inited').length:获取当前上传队列数量时,getFiles()需要带上‘inited’参数,才代表是初始状态的队列;
3、uploader.options.formData={}:设置json参数时这样才对;
‘贰’ webuploader上传成功后怎么删除
webuploader上传成功后可以通过输入删除程序进行删除。
‘叁’ 用webuploader怎么解决跨域上传文件的问题
跨域请求前浏览器会自动发出一个options请求,如果服务器的响应头部中有如下信息:
Access-Control-Allow-Origin: #允许访问的源,如http://localhost:3000
Access-Control-Allow-Methods: #允许的方法,如get, post
浏览器收到这个响应就会继续原来的请求,否则就会终止。
在webuploader中可以在uploadBeforeSend的回调中设置请求的头部,例如
uploader.on('uploadBeforeSend', function(obj, data, headers) {
_.extend(headers, {
"Origin": "http://localhost:3000",
"Access-Control-Request-Method": "POST"
});
});
在服务端的post响应中增加头部:Access-Control-Allow-Origin: http://localhost:3000
‘肆’ 上传控件 WebUploader 判断有没有上传成功
在认为成功前会派送一个事件uploadAccept,这个事件是用来询问是否上传成功的。在这个事件中你可以拿到上传的是哪个文件,以及对应的服务端返回reponse。
//如:上传成功返回 {"success" :"1"} //如:上传失败返回 {"success" :"0"}
uploader.on("uploadAccept", function( file, data){ if (
data.success=="0") { // 通过return false来告诉组件,此文件上传有错。 return false; } });
response是个对象,如果服务器返回是json格式,那么正和你意,都已经解析好了,如果不是json格式,response._raw里面可以拿到原始数据。所以,webuploader对于后端返回的数据格式是没有要求的。
上传控件 WebUploader 判断有没有上传成功
三者从本质上来说没有可比性,
socket则是对TCP/IP协议的封装和应用(程序员层面上)。
也可以说,TPC/IP协议是传输层协议,主要解决数据如何在网络中传输,
而HTTP是应用层协议,主要解决如何包装数据。
关于TCP/IP和HTTP协议的关系,网络有一段比较容易理解的介绍:
“我们在传输数据时,可以只使用(传输层)TCP/IP协议,但是那样的话,如果没有应用层,便无法识别数据内容。
如果想要使传输的数据有意义,则必须使用到应用层协议。
‘伍’ webuploader分片上传的实现代码(前后端分离)
本文介绍了webuploader分片上传的实现代码(前后端分离),分享给大家,具体如下:
WebUploader是由Bai
WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS
6+,
android
4+。两套运行时,同样的调用方式,可供用户任意选用。采用大文件分片并发上传,极大的提高了文件上传效率。(这个是从官网上直接的解释)
功能描述
1、webuploader是网络研发的上传组件,文档不是特别规整,但是也够用了。
2、前端使用官网的上传图片demo,在此基础上代码略微调整做分片。既可以上传图片也可以上传文件。文件超过分片大小才启用分片。
3、分片上传已做md5校验,达到秒传的效果。分片以后需要合并,可以先分片后合并,也可以边分片边合并,本示例采用的是边分片边合并的方案。
4、后端用springboot做框架搭建。springMVC做rest服务,开启跨域访问。
5、容器用springboot内置的tomcat插件,运行Application的main方法即可启动服务;
显示效果
关键代码前端
WebUploader.Uploader.register({
'name':
'webUploaderHookCommand',
'before-send-file':
'beforeSendFile',
"before-send":
"beforeSend"
},
{
beforeSendFile:
function(file)
{
var
task
=
new
WebUploader.Deferred();
fileName
=
file.name;
fileSize
=
file.size;
(new
WebUploader.Uploader()).md5File(file,
0,
10
*
1024
*
1024).progress(function(percentage)
{}).then(function(val)
{
fileMd5
=
val;
var
url
=
checkUrl;
var
data
=
{
type:
0,
fileName:
fileName,
fileMd5:
fileMd5,
fileSize:
fileSize
};
$.ajax({
type:
"POST",
url:
url,
data:
data,
cache:
false,
async:
false,
//
同步
timeout:
1000,
//
todo
超时的话,只能认为该分片未上传过
dataType:
"json",
error:
function(XMLHttpRequest,
textStatus,
errorThrown)
{
file.statusText
=
'server_error';
task.reject();
}
}).then(function(data,
textStatus,
jqXHR)
{
if(data.rtn
==
0)
{
if(data.obj
==
1)
{
file.statusText
=
'file_existed';
task.reject();
}
else
{
task.resolve();
}
}
else
{
task.reject();
}
});
});
return
task.promise();
},
beforeSend:
function(block)
{
var
task
=
new
WebUploader.Deferred();
var
url
=
checkUrl;
var
data
=
{
type:
1,
fileName:
fileName,
fileMd5:
fileMd5,
chunk:
block.chunk,
fileSize:
block.end
-
block.start
};
$.ajax({
type:
"POST",
url:
url,
data:
data,
cache:
false,
async:
false,
//
同步
timeout:
1000,
//
todo
超时的话,只能认为该分片未上传过
dataType:
"json"
}).then(function(data,
textStatus,
jqXHR)
{
if(data.rtn
==
0
&&
data.obj
==
1)
{
task.reject();
//
分片存在,则跳过上传
}
else
{
task.resolve();
}
});
this.owner.options.formData.fileMd5
=
fileMd5;
this.owner.options.formData.chunkSize
=
chunkSize;
return
task.promise();
}
});
//
实例化
uploader
=
WebUploader.create({
pick:
{
id:
'#filePicker',
label:
'点击选择文件'
},
formData:
{
uid:
123
},
dnd:
'#dndArea',
//指定文件拖拽的区域
paste:
'#uploader',
//指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为document.body.
swf:
'../plugins/webuploader/Uploader.swf',
chunked:
true,
chunkSize:
chunkSize,
chunkRetry:
false,
threads:
1,
server:
uploadUrl,
//
runtimeOrder:
'flash',
//
accept:
{
//
title:
'Images',
//
extensions:
'gif,jpg,jpeg,bmp,png',
//
mimeTypes:
'image/*'
//
},
//
禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
disableGlobalDnd:
true,
fileNumLimit:
300
//限制多文件上传的个数
//fileSizeLimit:
200
*
1024
*
1024,
//
限制所有文件的大小
200
M
//fileSingleSizeLimit:
50
*
1024
*
1024
//
限制单个文件的大小
50
M
});
后端
import
java.io.File;
import
java.io.IOException;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.beans.factory.annotation.Value;
import
org.springframework.stereotype.Service;
import
org.springframework.web.multipart.MultipartFile;
import
com.bear.upload.util.FileUtil;
import
com.bear.upload.util.RETURN;
import
com.bear.upload.vo.CheckMd5FileVO;
import
com.bear.upload.vo.UploadVO;
@Service
public
class
ChunkUploadService
{
private
static
Logger
LOG
=
LoggerFactory.getLogger(ChunkUploadService.class);
@Value("${file.upload.path}")
private
String
UPLOAD_PATH;
private
static
final
String
Delimiter
=
"-";
/**
*
上传之前校验(整个文件、分片)
*
*
@param
md5FileVO
*
@return
*/
public
Object
check(CheckMd5FileVO
md5FileVO)
{
Integer
type
=
md5FileVO.getType();
Long
chunk
=
md5FileVO.getChunk();
String
fileName
=
md5FileVO.getFileName();
Long
fileSize
=
md5FileVO.getFileSize();
if
(type
==
0)
{//
未分片校验
String
destfilePath
=
UPLOAD_PATH
+
File.separator
+
fileName;
File
destFile
=
new
File(destfilePath);
if
(destFile.exists()
&&
destFile.length()
==
fileSize)
{
return
RETURN.success("文件已存在,跳过",
1);
}
else
{
return
RETURN.success("文件不存在",
0);
}
}
else
{//
分片校验
String
fileMd5
=
md5FileVO.getFileMd5();
String
destFileDir
=
UPLOAD_PATH
+
File.separator
+
fileMd5;
String
destFileName
=
chunk
+
Delimiter
+
fileName;
String
destFilePath
=
destFileDir
+
File.separator
+
destFileName;
File
destFile
=
new
File(destFilePath);
if
(destFile.exists()
&&
destFile.length()
==
fileSize)
{
return
RETURN.success("分片已存在,跳过",
1);
}
else
{
return
RETURN.success("分片不存在",
0);
}
}
}
/**
*
文件上传
*
*
@param
file
*
@param
uploadVO
*
@param
appVersion
*
@return
*/
public
Object
upload(MultipartFile
file,
UploadVO
uploadVO)
{
Long
chunk
=
uploadVO.getChunk();
if
(chunk
==
null)
{//
没有分片
return
UnChunkUpload(file,
uploadVO);
}
else
{//
分片
return
ChunkUpload(file,
uploadVO);
}
}
/**
*
分片上传
*
*
@param
file
*
@param
uploadVO
*
@param
appVersion
*
@return
*/
public
Object
ChunkUpload(MultipartFile
file,
UploadVO
uploadVO)
{
String
fileName
=
uploadVO.getName();
String
fileMd5
=
uploadVO.getFileMd5();
Long
chunk
=
uploadVO.getChunk();//
当前片
Long
chunks
=
uploadVO.getChunks();//
总共多少片
//
分片目录创建
String
chunkDirPath
=
UPLOAD_PATH
+
File.separator
+
fileMd5;
File
chunkDir
=
new
File(chunkDirPath);
if
(!chunkDir.exists())
{
chunkDir.mkdirs();
}
//
分片文件上传
String
chunkFileName
=
chunk
+
Delimiter
+
fileName;
String
chunkFilePath
=
chunkDir
+
File.separator
+
chunkFileName;
File
chunkFile
=
new
File(chunkFilePath);
try
{
file.transferTo(chunkFile);
}
catch
(Exception
e)
{
LOG.error("分片上传出错",
e);
return
RETURN.fail("分片上传出错",
1);
}
//
合并分片
Long
chunkSize
=
uploadVO.getChunkSize();
long
seek
=
chunkSize
*
chunk;
String
destFilePath
=
UPLOAD_PATH
+
File.separator
+
fileName;
File
destFile
=
new
File(destFilePath);
if
(chunkFile.length()
>
0)
{
try
{
FileUtil.randomAccessFile(chunkFile,
destFile,
seek);
}
catch
(IOException
e)
{
LOG.error("分片{}合并失败:{}",
chunkFile.getName(),
e.getMessage());
return
RETURN.fail("分片合并失败",
1);
}
}
if
(chunk
==
chunks
-
1)
{
//
删除分片文件夹
FileUtil.deleteDirectory(chunkDirPath);
return
RETURN.success("上传成功",
1);
}
else
{
return
RETURN.fail("上传中...",
1);
}
}
/**
*
未分片上传
*
*
@param
file
*
@param
uploadVO
*
@param
appVersion
*
@return
*/
public
Object
UnChunkUpload(MultipartFile
file,
UploadVO
uploadVO)
{
String
fileName
=
uploadVO.getName();
//
String
fileMd5
=
uploadVO.getFileMd5();
//
文件上传
File
destFile
=
new
File(UPLOAD_PATH
+
File.separator
+
fileName);
if
(file
!=
null
&&
!file.isEmpty())
{
//
上传目录
File
fileDir
=
new
File(UPLOAD_PATH);
if
(!fileDir.exists())
{
fileDir.mkdirs();
}
if
(destFile.exists())
{
destFile.delete();
}
try
{
file.transferTo(destFile);
return
RETURN.success("上传成功",
0);
}
catch
(Exception
e)
{
LOG.error("文件上传出错",
e);
return
RETURN.fail("文件上传出错",
0);
}
}
return
RETURN.fail("上传失败",
0);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:Vue2.0结合webuploader实现文件分片上传功能使用WebUploader实现分片断点上传文件功能(二)webuploader在springMVC+jquery+Java开发环境下的大文件分片上传的实例代码jQuery
webuploader分片上传大文件
‘陆’ webuploader上传成功后怎么删除
<div id="uploader">
<div class="queueList">
<div id="dndArea" class="placeholder">
<div id="filePicker"></div>
<p>或将照片拖到这里,单次最多可选30张</p>
</div>
</div>
<div class="statusBar" style="display:none;">
<div class="progress">
<span class="text">0%</span>
<span class="percentage"></span>
</div><div class="info"></div>
<div class="btns">
<div id="filePicker2"></div><div class="uploadBtn">开始上传</div>
</div>
</div>
</div>
<script>
require(['jquery', 'webuploader' ], function($, WebUploader) {
return;
// 当domReady的时候开始初始化
$(function() {
var $wrap = $('#uploader'),
// 图片容器
$queue = $( '<ul class="filelist"></ul>' )
.appendTo( $wrap.find( '.queueList' ) ),
// 状态栏,包括进度和控制按钮
$statusBar = $wrap.find( '.statusBar' ),
// 文件总体选择信息。
$info = $statusBar.find( '.info' ),
// 上传按钮
$upload = $wrap.find( '.uploadBtn' ),
// 没选择文件之前的内容。
$placeHolder = $wrap.find( '.placeholder' ),
$progress = $statusBar.find( '.progress' ).hide(),
// 添加的文件数量
fileCount = 0,
// 添加的文件总大小
fileSize = 0,
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 110 * ratio,
thumbnailHeight = 110 * ratio,
// 可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 所有文件的进度信息,key为file id
percentages = {},
supportTransition = (function(){
var s = document.createElement('p').style,
r = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
s = null;
return r;
})(),
// WebUploader实例
uploader;
// 实例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '点击选择图片'
},
dnd: '#dndArea',
paste: '#uploader',
// swf文件路径
swf: '{$_W['siteroot']}app/resource/componets/webuploader/Uploader.swf',
// 文件接收服务端。
server: '{$_W['siteroot']}app/{php echo str_replace('./','',url('utility/file',array('do'=>'upload', 'type'=>'image'), true))}',
chunked: true,
// runtimeOrder: 'flash',
// sendAsBinary: true,
fileNumLimit: 30,
fileSizeLimit: 30 * 1024 * 1024, // 30 M
fileSingleSizeLimit: 4 * 1024 * 1024 // 1 M
});
// 添加“添加文件”的按钮,
uploader.addButton({
id: '#filePicker2',
label: '继续添加'
});
// 当有文件添加进来时执行,负责view的创建
function addFile( file ) {
var $li = $( '<li id="' + file.id + '">' +
'<p class="title">' + file.name + '</p>' +
'<p class="imgWrap"></p>'+
'<p class="progress"><span></span></p>' +
'</li>' ),
$btns = $('<div class="file-panel">' +
'<span class="cancel">删除</span>' +
'<span class="rotateRight">向右旋转</span>' +
'<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
$prgress = $li.find('p.progress span'),
$wrap = $li.find( 'p.imgWrap' ),
$info = $('<p class="error"></p>'),
showError = function( code ) {
switch( code ) {
case 'exceed_size':
text = '文件大小超出';
break;
case 'interrupt':
text = '上传暂停';
break;
default:
text = '上传失败,请重试';
break;
}
$info.text( text ).appendTo( $li );
};
if ( file.getStatus() === 'invalid' ) {
showError( file.statusText );
} else {
// @todo lazyload
$wrap.text( '预览中' );
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$wrap.text( '不能预览' );
return;
}
var img = $('<img src="'+src+'">');
$wrap.empty().append( img );
}, thumbnailWidth, thumbnailHeight );
percentages[ file.id ] = [ file.size, 0 ];
file.rotation = 0;
}
file.on('statuschange', function( cur, prev ) {
if ( prev === 'progress' ) {
$prgress.hide().width(0);
} else if ( prev === 'queued' ) {
$li.off( 'mouseenter mouseleave' );
$btns.remove();
}
// 成功
if ( cur === 'error' || cur === 'invalid' ) {
console.log( file.statusText );
showError( file.statusText );
percentages[ file.id ][ 1 ] = 1;
} else if ( cur === 'interrupt' ) {
showError( 'interrupt' );
} else if ( cur === 'queued' ) {
percentages[ file.id ][ 1 ] = 0;
} else if ( cur === 'progress' ) {
$info.remove();
$prgress.css('display', 'block');
} else if ( cur === 'complete' ) {
$li.append( '<span class="success"></span>' );
}
$li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
});
$li.on( 'mouseenter', function() {
$btns.stop().animate({height: 30});
});
$li.on( 'mouseleave', function() {
$btns.stop().animate({height: 0});
});
$btns.on( 'click', 'span', function() {
var index = $(this).index(),
deg;
switch ( index ) {
case 0:
uploader.removeFile( file );
return;
case 1:
file.rotation += 90;
break;
case 2:
file.rotation -= 90;
break;
}
if ( supportTransition ) {
deg = 'rotate(' + file.rotation + 'deg)';
$wrap.css({
'-webkit-transform': deg,
'-mos-transform': deg,
'-o-transform': deg,
'transform': deg
});
} else {
$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
}
});
$li.appendTo( $queue );
}
// 负责view的销毁
function removeFile( file ) {
var $li = $('#'+file.id);
delete percentages[ file.id ];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
function updateTotalProgress() {
var loaded = 0,
total = 0,
spans = $progress.children(),
percent;
$.each( percentages, function( k, v ) {
total += v[ 0 ];
loaded += v[ 0 ] * v[ 1 ];
} );
percent = total ? loaded / total : 0;
spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
updateStatus();
}
function updateStatus() {
var text = '', stats;
if ( state === 'ready' ) {
text = '选中' + fileCount + '张图片,共' + WebUploader.formatSize( fileSize ) + '。';
} else if ( state === 'confirm' ) {
stats = uploader.getStats();
if ( stats.uploadFailNum ) {
text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
}
} else {
stats = uploader.getStats();
text = '共' + fileCount + '张(' +
WebUploader.formatSize( fileSize ) +
'),已上传' + stats.successNum + '张';
if ( stats.uploadFailNum ) {
text += ',失败' + stats.uploadFailNum + '张';
}
}
$info.html( text );
}
function setState( val ) {
var file, stats;
if ( val === state ) {
return;
}
$upload.removeClass( 'state-' + state );
$upload.addClass( 'state-' + val );
state = val;
switch ( state ) {
case 'pedding':
$placeHolder.removeClass( 'element-invisible' );
$queue.hide();
$statusBar.addClass( 'element-invisible' );
uploader.refresh();
break;
case 'ready':
$placeHolder.addClass( 'element-invisible' );
$( '#filePicker2' ).removeClass( 'element-invisible');
$queue.show();
$statusBar.removeClass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$( '#filePicker2' ).addClass( 'element-invisible' );
$progress.show();
$upload.text( '暂停上传' );
break;
case 'paused':
$progress.show();
$upload.text( '继续上传' );
break;
case 'confirm':
$progress.hide();
$upload.text( '开始上传' ).addClass( 'disabled' );
stats = uploader.getStats();
if ( stats.successNum && !stats.uploadFailNum ) {
setState( 'finish' );
return;
}
break;
case 'finish':
stats = uploader.getStats();
if ( stats.successNum ) {
alert( '上传成功' );
} else {
// 没有成功的图片,重设
state = 'done';
location.reload();
}
break;
}
updateStatus();
}
uploader.onUploadProgress = function( file, percentage ) {
var $li = $('#'+file.id),
$percent = $li.find('.progress span');
$percent.css( 'width', percentage * 100 + '%' );
percentages[ file.id ][ 1 ] = percentage;
updateTotalProgress();
};
uploader.onFileQueued = function( file ) {
fileCount++;
fileSize += file.size;
if ( fileCount === 1 ) {
$placeHolder.addClass( 'element-invisible' );
$statusBar.show();
}
addFile( file );
setState( 'ready' );
updateTotalProgress();
};
uploader.onFileDequeued = function( file ) {
fileCount--;
fileSize -= file.size;
if ( !fileCount ) {
setState( 'pedding' );
}
removeFile( file );
updateTotalProgress();
};
uploader.on( 'all', function( type ) {
var stats;
switch( type ) {
case 'uploadFinished':
setState( 'confirm' );
break;
case 'startUpload':
setState( 'uploading' );
break;
case 'stopUpload':
setState( 'paused' );
break;
}
});
uploader.onError = function( code ) {
alert( 'Eroor: ' + code );
};
$upload.on('click', function() {
if ( $(this).hasClass( 'disabled' ) ) {
return false;
}
if ( state === 'ready' ) {
uploader.upload();
} else if ( state === 'paused' ) {
uploader.upload();
} else if ( state === 'uploading' ) {
uploader.stop();
}
});
$info.on( 'click', '.retry', function() {
uploader.retry();
} );
$info.on( 'click', '.ignore', function() {
alert( 'todo' );
} );
$upload.addClass( 'state-' + state );
updateTotalProgress();
});
});
</script>
‘柒’ webuploader用java怎么接收
webuploader用java接收:
<div id="uploader" class="wu-example">
<div class="queueList">
<div id="dndArea" class="placeholder">
<div id="filePicker"></div>
<p>或将照片拖到这里,单次最多可选300张</p>
</div>
</div>
<div class="statusBar" style="display: none;">
<div class="progress">
<span class="text">0%</span> <span class="percentage"></span>
</div>
<div class="info"></div>
<div class="btns">
<div id="filePicker2"></div>
<div class="uploadBtn">开始上传</div>
</div>
</div>
</div>
<!-- webuploader -->
<link rel="stylesheet" type="text/css"
href="/static/js/webuploader/css.css">
<link rel="stylesheet" type="text/css"
href="/static/js/webuploader/image.css">
<script type="text/javascript" src="/static/js/webuploader/min.js"></script>
<script type="text/javascript"
src="/static/js/webuploader/upload-image.js"></script>
Js代码
// 实例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '点击选择图片'
},
dnd: '#uploader .queueList',
paste: document.body,
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
},
// swf文件路径
[color=red]swf: '/static/js/webuploader/Uploader.swf',[/color]
disableGlobalDnd: true,
chunked: true,
server: '/point/image/bulk.html',
fileNumLimit: 300,
fileSizeLimit: 50*1024*1024,//5M
fileSingleSizeLimit: 5*1024*1024 //1M
});
上传文件和普通的spring一样
Java代码
@RequestMapping("/bulk")
@ResponseBody
public String bulk(HttpServletRequest request, MultipartFile file) {
String path = super.uploadFile(request, "file", true);
return "1";
}
引用
Spring MVC3.2开始支持通过Servlet3.0实现文件上传
Xml代码
<bean id="multipartResolver"class="org.springframework.web.multipart.support."></bean>