首页技术webuploader asp.net 如何使用百度的webuploader

webuploader asp.net 如何使用百度的webuploader

编程之家2023-11-01144次浏览

你是否对于webuploader和asp.net 如何使用百度的webuploader感到困惑?别担心,今天小编将为您揭开这个谜团,让我们一同探索吧!

webuploader asp.net 如何使用百度的webuploader

webuploader 上传文件php怎么接受

使用

使用webuploader分成简单直选要引入

<!--引入CSS-->

<link rel="stylesheet" type="text/css" rel="external nofollow" href="webuploader文件夹/webuploader.css">

webuploader asp.net 如何使用百度的webuploader

<!--引入JS-->

<script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

HTML部分

<div id="uploader" class="wu-example">

<!--用来存放文件信息-->

<div id="thelist" class="uploader-list"></div>

webuploader asp.net 如何使用百度的webuploader

<div class="btns">

<div id="picker">选择文件</div>

<button id="ctlBtn" class="btn btn-default">开始上传</button>

</div>

</div>

初始化Web Uploader

jQuery(function(){

$list=$('#thelist'),

$btn=$('#ctlBtn'),

state='pending',

uploader;

uploader= WebUploader.create({

//不压缩image

resize: false,

// swf文件路径

swf:'uploader.swf',

//文件接收服务端。

server: upload.php,

//选择文件的按钮。可选。

//内部根据当前运行是创建,可能是input元素,也可能是flash.

pick:'#picker',

chunked: true,

chunkSize:2*1024*1024,

auto: true,

accept:{

title:'Images',

extensions:'gif,jpg,jpeg,bmp,png',

mimeTypes:'image/*'

}

});

upload.php处理

以下是根据别人的例子自己拿来改的php后台代码

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

header("Last-Modified:". gmdate("D, d M Y H:i:s")." GMT");

header("Cache-Control: no-store, no-cache, must-revalidate");

header("Cache-Control: post-check=0, pre-check=0", false);

header("Pragma: no-cache");

if($_SERVER['REQUEST_METHOD']=='OPTIONS'){

exit;// finish preflight CORS requests here

}

if(!empty($_REQUEST['debug' ])){

$random= rand(0, intval($_REQUEST['debug' ]));

if($random=== 0){

header("HTTP/1.0 500 Internal Server Error");

exit;

}

}

// header("HTTP/1.0 500 Internal Server Error");

// exit;

// 5 minutes execution time

@set_time_limit(5* 60);

// Uncomment this one to fake upload time

// usleep(5000);

// Settings

//$targetDir= ini_get("upload_tmp_dir"). DIRECTORY_SEPARATOR."plupload";

$targetDir='uploads'.DIRECTORY_SEPARATOR.'file_material_tmp';

$uploadDir='uploads'.DIRECTORY_SEPARATOR.'file_material';

$cleanupTargetDir= true;// Remove old files

$maxFileAge= 5* 3600;// Temp file age in seconds

// Create target dir

if(!file_exists($targetDir)){

@mkdir($targetDir);

}

// Create target dir

if(!file_exists($uploadDir)){

@mkdir($uploadDir);

}

// Get a file name

if(isset($_REQUEST["name"])){

$fileName=$_REQUEST["name"];

} elseif(!empty($_FILES)){

$fileName=$_FILES["file"]["name"];

} else{

$fileName= uniqid("file_");

}

$oldName=$fileName;

$filePath=$targetDir. DIRECTORY_SEPARATOR.$fileName;

//$uploadPath=$uploadDir. DIRECTORY_SEPARATOR.$fileName;

// Chunking might be enabled

$chunk= isset($_REQUEST["chunk"])? intval($_REQUEST["chunk"]): 0;

$chunks= isset($_REQUEST["chunks"])? intval($_REQUEST["chunks"]): 1;

// Remove old temp files

if($cleanupTargetDir){

if(!is_dir($targetDir)||!$dir= opendir($targetDir)){

die('{"jsonrpc":"2.0","error":{"code": 100,"message":"Failed to open temp directory."},"id":"id"}');

}

while(($file= readdir($dir))!== false){

$tmpfilePath=$targetDir. DIRECTORY_SEPARATOR.$file;

// If temp file is current file proceed to the next

if($tmpfilePath=="{$filePath}_{$chunk}.part"||$tmpfilePath=="{$filePath}_{$chunk}.parttmp"){

continue;

}

// Remove temp file if it is older than the max age and is not the current file

if(preg_match('/\.(part|parttmp)$/',$file)&&(@filemtime($tmpfilePath)< time()-$maxFileAge)){

@unlink($tmpfilePath);

}

}

closedir($dir);

}

// Open temp file

if(!$out=@fopen("{$filePath}_{$chunk}.parttmp","wb")){

die('{"jsonrpc":"2.0","error":{"code": 102,"message":"Failed to open output stream."},"id":"id"}');

}

if(!empty($_FILES)){

if($_FILES["file"]["error"]||!is_uploaded_file($_FILES["file"]["tmp_name"])){

die('{"jsonrpc":"2.0","error":{"code": 103,"message":"Failed to move uploaded file."},"id":"id"}');

}

// Read binary input stream and append it to temp file

if(!$in=@fopen($_FILES["file"]["tmp_name"],"rb")){

die('{"jsonrpc":"2.0","error":{"code": 101,"message":"Failed to open input stream."},"id":"id"}');

}

} else{

if(!$in=@fopen("php://input","rb")){

die('{"jsonrpc":"2.0","error":{"code": 101,"message":"Failed to open input stream."},"id":"id"}');

}

}

while($buff= fread($in, 4096)){

fwrite($out,$buff);

}

@fclose($out);

@fclose($in);

rename("{$filePath}_{$chunk}.parttmp","{$filePath}_{$chunk}.part");

$index= 0;

$done= true;

for($index= 0;$index<$chunks;$index++){

if(!file_exists("{$filePath}_{$index}.part")){

$done= false;

break;

}

}

if($done){

$pathInfo= pathinfo($fileName);

$hashStr= substr(md5($pathInfo['basename']),8,16);

$hashName= time().$hashStr.'.'.$pathInfo['extension'];

$uploadPath=$uploadDir. DIRECTORY_SEPARATOR.$hashName;

if(!$out=@fopen($uploadPath,"wb")){

die('{"jsonrpc":"2.0","error":{"code": 102,"message":"Failed to open output stream."},"id":"id"}');

}

if( flock($out, LOCK_EX)){

for($index= 0;$index<$chunks;$index++){

if(!$in=@fopen("{$filePath}_{$index}.part","rb")){

break;

}

while($buff= fread($in, 4096)){

fwrite($out,$buff);

}

@fclose($in);

@unlink("{$filePath}_{$index}.part");

}

flock($out, LOCK_UN);

}

@fclose($out);

$response= [

'success'=>true,

'oldName'=>$oldName,

'filePaht'=>$uploadPath,

'fileSize'=>$data['size'],

'fileSuffixes'=>$pathInfo['extension'],

'file_id'=>$data['id'],

];

die(json_encode($response));

}

// Return Success JSON-RPC response

die('{"jsonrpc":"2.0","result": null,"id":"id"}');

asp.net 如何使用百度的webuploader

asp.net的服务器端的自己重新写一个服务,下载下来的是一个php的写的,将下载的代码进行如下修改(这里使用的是demo中的image-upload):

首先,找到109行的代码

varswf='./expressInstall.swf';

修改为您的地址

//修改您的flash地址

varswf='./Scripts/webuploader-0.1.5/examples/image-upload/expressInstall.swf';

其次,找到151行,在实例化的时候修改用于上传flash的地址:

swf:'../../dist/Uploader.swf',

修改为

swf:'./Scripts/webuploader-0.1.5/dist/Uploader.swf',

第三,找到154行,将图片上传地址修改为.net的一般处理程序的请求地址

server:'../../server/fileupload.php',

修改为您的一般处理程序地址

server:'./server/fileupload.ashx',

第四,找到260行修改预览的服务器代码地址(我没有写不影响文件上传)

$.ajax('../../server/preview.php',{

修改为您的一般处理程序的预览地址

$.ajax('./server/preview.ashx',{

好了,到这里我们将upload.js修改完成了。

下面就是写了处理程序了,在项目中创建一个server文件夹并添加以下两个文件fileupload.ashx和preview.ashx。

下面介绍fileupload.ashx的实现方法

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Web;

usingSystem.IO;

usingSystem.Text;

namespaceBlog.server

{

///<summary>

///Summarydescriptionforfileupload

///</summary>

publicclassfileupload:IHttpHandler

{

publicvoidProcessRequest(HttpContextcontext)

{

context.Response.ContentType="text/plain";

//指定字符集

context.Response.ContentEncoding=Encoding.UTF8;

if(context.Request["REQUEST_METHOD"]=="OPTIONS")

{

context.Response.End();

}

SaveFile();

}

///<summary>

///文件保存操作

///</summary>

///<paramname="basePath"></param>

privatevoidSaveFile(stringbasePath="~/Upload/Images/")

{

varname=string.Empty;

basePath=(basePath.IndexOf("~")>-1)?System.Web.HttpContext.Current.Server.MapPath(basePath):

basePath;

HttpFileCollectionfiles=System.Web.HttpContext.Current.Request.Files;

//如果目录不存在,则创建目录

if(!Directory.Exists(basePath))

{

Directory.CreateDirectory(basePath);

}

varsuffix=files[0].ContentType.Split('/');

//获取文件格式

var_suffix=suffix[1].Equals("jpeg",StringComparison.CurrentCultureIgnoreCase)?"":suffix[1];

var_temp=System.Web.HttpContext.Current.Request["name"];

//如果不修改文件名,则创建随机文件名

if(!string.IsNullOrEmpty(_temp))

{

name=_temp;

}

else

{

Randomrand=newRandom(24*(int)DateTime.Now.Ticks);

name=rand.Next()+"."+_suffix;

}

//文件保存

varfull=basePath+name;

files[0].SaveAs(full);

var_result="{\"jsonrpc\":\"2.0\",\"result\":null,\"id\":\""+name+"\"}";

System.Web.HttpContext.Current.Response.Write(_result);

}

publicboolIsReusable

{

get

{

returnfalse;

}

}

}

}

运行效果如下:

上传成功了,下面来看看文件是否被保存了,打开文件件查看如下;

Perfect!正如完美预料的那样成功了。谢谢!!!!

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" rel="external nofollow" rel="external nofollow" href="#">重新上传</a>失败图片或<a class="ignore" rel="external nofollow" rel="external nofollow" 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和asp.net 如何使用百度的webuploader的答案你都知道了吗?欢迎再次光临本站哦!

seo分析,seo分析是什么网站建设企业建站?做网站建设哪家好