jquery文件上传控件 WebUploader

WebUploader是百度开源的一个文件上传组件,因为其操作简洁大方,就在项目中使用了,记录一下。 

效果是这样子: 
jquery文件上传控件 WebUploader 
这个样子是默认的效果。

jquery文件上传控件 WebUploader 
这个是选择上传的图片,可以批量,选择后可以删除和添加更多。

jquery文件上传控件 WebUploader 
这个是上传过程显示的效果。

 
  1. <div id="container">

  2. <!--头部,相册选择和格式选择-->

  3. <div id="uploader">

  4. <div class="queueList">

  5. <div id="dndArea" class="placeholder">

  6. <div id="filePicker"></div>

  7. <p><s:text name="resource.upload.tip"/></p>

  8. </div>

  9. </div>

  10. <div class="statusBar" style="display:none;">

  11. <div class="progress">

  12. <span class="text">0%</span>

  13. <span class="percentage"></span>

  14. </div>

  15. <div class="info"></div>

  16. <div class="btns">

  17. <div id="filePicker2"></div>

  18. <div class="uploadBtn"><s:text name="resource.starttoupload"></s:text></div>

  19. </div>

  20. </div>

  21. </div>

  22. </div>

js部分代码,下面这段代码是webuploader官方的示例代码uploader.js做的修改:

 
  1. (function( $ ){

  2. // 当domReady的时候开始初始化

  3. $(function() {

  4. var filePerSize = [];//每个文件大小

  5. var fileName = [];

  6. var fileSize = 0;

  7.  
  8. var $wrap = $('#uploader'),

  9.  
  10. // 图片容器

  11. $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')),

  12.  
  13. // 状态栏,包括进度和控制按钮

  14. $statusBar = $wrap.find('.statusBar'),

  15.  
  16. // 文件总体选择信息。

  17. $info = $statusBar.find('.info'),

  18.  
  19. // 上传按钮

  20. $upload = $wrap.find('.uploadBtn'),

  21.  
  22. // 没选择文件之前的内容。

  23. $placeHolder = $wrap.find('.placeholder'),

  24.  
  25. $progress = $statusBar.find('.progress').hide(),

  26.  
  27. // 添加的文件数量

  28. fileCount = 0,

  29.  
  30. // 添加的文件总大小

  31. fileSize = 0,

  32.  
  33. // 优化retina, 在retina下这个值是2

  34. ratio = window.devicePixelRatio || 1,

  35.  
  36. // 缩略图大小

  37. thumbnailWidth = 110 * ratio,

  38. thumbnailHeight = 110 * ratio,

  39.  
  40. // 可能有pedding, ready, uploading, confirm, done.

  41. state = 'pedding',

  42.  
  43. // 所有文件的进度信息,key为file id

  44. percentages = {},

  45. // 判断浏览器是否支持图片的base64

  46. isSupportBase64 = ( function() {

  47. var data = new Image();

  48. var support = true;

  49. data.onload = data.onerror = function() {

  50. if( this.width != 1 || this.height != 1 ) {

  51. support = false;

  52. }

  53. }

  54. data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";

  55. return support;

  56. })(),

  57.  
  58. // 检测是否已经安装flash,检测flash的版本

  59. flashVersion = ( function() {

  60. var version;

  61. try {

  62. version = navigator.plugins[ 'Shockwave Flash' ];

  63. version = version.description;

  64. } catch ( ex ) {

  65. try {

  66. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')

  67. .GetVariable('$version');

  68. } catch ( ex2 ) {

  69. version = '0.0';

  70. }

  71. }

  72. version = version.match( /\d+/g );

  73. return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );

  74. } )(),

  75.  
  76. supportTransition = (function(){

  77. var s = document.createElement('p').style,

  78. r = 'transition' in s ||

  79. 'WebkitTransition' in s ||

  80. 'MozTransition' in s ||

  81. 'msTransition' in s ||

  82. 'OTransition' in s;

  83. s = null;

  84. return r;

  85. })(),

  86.  
  87. // WebUploader实例

  88. uploader;

  89.  
  90. if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {

  91. // flash 安装了但是版本过低。

  92. if (flashVersion) {

  93. (function(container) {

  94. window['expressinstallcallback'] = function( state ) {

  95. switch(state) {

  96. case 'Download.Cancelled':

  97. //alert('您取消了更新!')

  98. break;

  99.  
  100. case 'Download.Failed':

  101. //alert('安装失败')

  102. break;

  103.  
  104. default:

  105. //alert('安装已成功,请刷新!');

  106. break;

  107. }

  108. delete window['expressinstallcallback'];

  109. };

  110.  
  111. var swf = './expressInstall.swf';

  112. // insert flash object

  113. var html = '<object type="application/' +

  114. 'x-shockwave-flash" data="' + swf + '" ';

  115.  
  116. if (WebUploader.browser.ie) {

  117. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';

  118. }

  119.  
  120. html += 'width="100%" height="100%" style="outline:0">' +

  121. '<param name="movie" value="' + swf + '" />' +

  122. '<param name="wmode" value="transparent" />' +

  123. '<param name="allowscriptaccess" value="always" />' +

  124. '</object>';

  125.  
  126. container.html(html);

  127. })($wrap);

  128.  
  129. // 压根就没有安转。

  130. } else {

  131. $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');

  132. }

  133.  
  134. return;

  135. } else if (!WebUploader.Uploader.support()) {

  136. alert( 'Web Uploader not support your browser!');

  137. return;

  138. }

  139.  
  140. // 实例化

  141. uploader = WebUploader.create({

  142. pick: {

  143. id: '#filePicker',

  144. name: 'multiFile',

  145. label: 'Click To Select'

  146. },

  147. formData: {

  148. "status": "multi",

  149. "contentsDto.contentsId": "xxxx",

  150. "uploadNum": "xxxx",

  151. "existFlg": "false",

  152. },

  153. dnd: '#dndArea',

  154. paste: '#uploader',

  155. method: 'POST',

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

  157. chunked: false,

  158. chunkSize: 512 * 1024,

  159. chunkRetry:false,

  160. server: 'resource/upload.action?resourcetype=hd',

  161. fileVal:'multiFile',

  162. resize: false,

  163. // runtimeOrder: 'flash',

  164.  
  165. /* accept: {

  166. title: 'Images',

  167. extensions: 'gif,jpg,bmp,png,m2v',

  168. mimeTypes: 'image/*,video/mpeg',

  169. }, */

  170.  
  171. // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。

  172. disableGlobalDnd: true,

  173. fileNumLimit: 300,

  174. fileSizeLimit: 200 * 1024 * 1024, // 200 M

  175. fileSingleSizeLimit: 50 * 1024 * 1024 // 50 M

  176. });

  177.  
  178. // 拖拽时不接受 js, txt 文件。

  179. uploader.on('dndAccept', function( items ) {

  180. var denied = false,

  181. len = items.length,

  182. i = 0,

  183. // 修改js类型

  184. unAllowed = 'text/plain;application/javascript ';

  185.  
  186. for ( ; i < len; i++ ) {

  187. // 如果在列表里面

  188. if ( ~unAllowed.indexOf( items[ i ].type ) ) {

  189. denied = true;

  190. break;

  191. }

  192. }

  193. return !denied;

  194. });

  195.  
  196. //点击按钮弹出选择框

  197. /*uploader.on('dialogOpen', function() {

  198. console.log('here');

  199. });*/

  200.  
  201. // 添加"添加文件"的按钮,

  202. uploader.addButton({

  203. id: '#filePicker2',

  204. label: '<s:text name="resource.addmore"></s:text>'

  205. });

  206.  
  207. uploader.on('ready', function() {

  208. window.uploader = uploader;

  209. });

  210.  
  211. // 当有文件添加进来时执行,负责view的创建

  212. function addFile( file ) {

  213. var $li = $( '<li id="' + file.id + '">' +

  214. '<p class="title">' + file.name + '</p>' +

  215. '<p class="imgWrap"></p>'+

  216. '<p class="progress"><span></span></p>' +

  217. '</li>' ),

  218.  
  219. $btns = $('<div class="file-panel">' +

  220. '<span class="cancel"><s:text name="resource.delete"></s:text></span>' +

  221. '<span class="rotateRight"><s:text name="resource.rotateToRight"></s:text></span>' +

  222. '<span class="rotateLeft"><s:text name="resource.rotateToLeft"></s:text></span></div>').appendTo( $li ),

  223. $prgress = $li.find('p.progress span'),

  224. $wrap = $li.find( 'p.imgWrap' ),

  225. $info = $('<p class="error"></p>'),

  226.  
  227. showError = function( code ) {

  228. switch( code ) {

  229. case 'exceed_size':

  230. text = '<s:text name="resource.exceedSize"></s:text>';

  231. break;

  232.  
  233. case 'interrupt':

  234. text = '<s:text name="resource.pauseupload"></s:text>';

  235. break;

  236.  
  237. default:

  238. text = '<s:text name="resource.uploadfailed"></s:text>';

  239. break;

  240. }

  241.  
  242. $info.text( text ).appendTo( $li );

  243. };

  244.  
  245. if ( file.getStatus() === 'invalid' ) {

  246. showError( file.statusText );

  247. } else {

  248. // @todo lazyload

  249. $wrap.text( '<s:text name="resource.onPreview"></s:text>' );

  250. uploader.makeThumb( file, function( error, src ) {

  251. var img;

  252.  
  253. if ( error ) {

  254. $wrap.text( '<s:text name="resource.unablePreview"></s:text>' );

  255. return;

  256. }

  257.  
  258. if( isSupportBase64 ) {

  259. img = $('<img src="'+src+'">');

  260. $wrap.empty().append( img );

  261. } else {

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

  263. method: 'POST',

  264. data: src,

  265. dataType:'json'

  266. }).done(function( response ) {

  267. if (response.result) {

  268. img = $('<img src="'+response.result+'">');

  269. $wrap.empty().append( img );

  270. } else {

  271. $wrap.text("预览出错");

  272. }

  273. });*/

  274. }

  275. }, thumbnailWidth, thumbnailHeight );

  276.  
  277. percentages[ file.id ] = [ file.size, 0 ];

  278. file.rotation = 0;

  279. }

  280.  
  281. file.on('statuschange', function( cur, prev ) {

  282. if ( prev === 'progress' ) {

  283. $prgress.hide().width(0);

  284. } else if ( prev === 'queued' ) {

  285. $li.off( 'mouseenter mouseleave' );

  286. $btns.remove();

  287. }

  288. // 成功

  289. if (cur === 'error' || cur === 'invalid') {

  290. console.log( file.statusText );

  291. showError( file.statusText );

  292. percentages[ file.id ][ 1 ] = 1;

  293. } else if ( cur === 'interrupt' ) {

  294. showError( 'interrupt' );

  295. } else if ( cur === 'queued' ) {

  296. $info.remove();

  297. $prgress.css('display', 'block');

  298. percentages[ file.id ][ 1 ] = 0;

  299. } else if ( cur === 'progress' ) {

  300. $info.remove();

  301. $prgress.css('display', 'block');

  302. } else if ( cur === 'complete' ) {

  303. $prgress.hide().width(0);

  304. $li.append('<span class="success"></span>');

  305. }

  306.  
  307. $li.removeClass('state-' + prev).addClass('state-' + cur);

  308. });

  309.  
  310. $li.on('mouseenter', function() {

  311. $btns.stop().animate({height: 30});

  312. });

  313.  
  314. $li.on('mouseleave', function() {

  315. $btns.stop().animate({height: 0});

  316. });

  317.  
  318. $btns.on('click', 'span', function() {

  319. var index = $(this).index(),

  320. deg;

  321. switch (index) {

  322. case 0:

  323. uploader.removeFile( file );

  324. return;

  325.  
  326. case 1:

  327. file.rotation += 90;

  328. break;

  329.  
  330. case 2:

  331. file.rotation -= 90;

  332. break;

  333. }

  334. if (supportTransition) {

  335. deg = 'rotate(' + file.rotation + 'deg)';

  336. $wrap.css({

  337. '-webkit-transform': deg,

  338. '-mos-transform': deg,

  339. '-o-transform': deg,

  340. 'transform': deg

  341. });

  342. } else {

  343. $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');

  344. }

  345. });

  346. $li.appendTo($queue);

  347. }

  348.  
  349. // 负责view的销毁

  350. function removeFile( file ) {

  351. var $li = $('#'+file.id);

  352.  
  353. delete percentages[ file.id ];

  354. updateTotalProgress();

  355. $li.off().find('.file-panel').off().end().remove();

  356. }

  357.  
  358. function updateTotalProgress() {

  359. var loaded = 0,

  360. total = 0,

  361. spans = $progress.children(),

  362. percent;

  363. $.each( percentages, function( k, v ) {

  364. total += v[ 0 ];

  365. loaded += v[ 0 ] * v[ 1 ];

  366. } );

  367.  
  368. percent = total ? loaded / total : 0;

  369. spans.eq( 0 ).text(Math.round( percent * 100 ) + '%');

  370. spans.eq( 1 ).css('width', Math.round( percent * 100 ) + '%');

  371. updateStatus();

  372. }

  373.  
  374. function updateStatus() {

  375. var text = '', stats;

  376. if ( state === 'ready' ) {

  377. text = '<s:text name="resource.selected"></s:text>' + fileCount + ', <s:text name="resource.totalSize"></s:text>' +

  378. WebUploader.formatSize(fileSize);

  379. } else if ( state === 'confirm' ) {

  380. stats = uploader.getStats();

  381. if ( stats.uploadFailNum ) {

  382. text = '<s:text name="resource.uploaded"></s:text>' + stats.successNum+ ', <s:text name="resource.failed"></s:text>'+

  383. stats.uploadFailNum + ', <a class="retry" href="#" style="color:red;">' + '<s:text name="resource.retry"></s:text>'+'</a>&nbsp;<s:text name="resource.or"></s:text><a class="ignore" href="#" style="color:blue;">&nbsp;<s:text name="resource.ignore"></s:text></a>'

  384. }

  385. } else {

  386. stats = uploader.getStats();

  387. text = '<s:text name="resource.total"></s:text>' + fileCount + '(' +

  388. WebUploader.formatSize( fileSize ) +

  389. '), <s:text name="resource.uploaded"></s:text>:' + stats.successNum;

  390.  
  391. if ( stats.uploadFailNum ) {

  392. text += ', <s:text name="resource.failed"></s:text>:' + stats.uploadFailNum;

  393. }

  394. }

  395. $info.html(text);

  396. }

  397.  
  398. /*关闭上传框窗口后恢复上传框初始状态*/

  399. function closeUploader() {

  400. // 移除所有缩略图并将上传文件移出上传序列

  401. for (var i = 0; i < uploader.getFiles().length; i++) {

  402. // 将图片从上传序列移除

  403. uploader.removeFile(uploader.getFiles()[i]);

  404. // 将图片从缩略图容器移除

  405. var $li = $('#' + uploader.getFiles()[i].id);

  406. $li.off().remove();

  407. }

  408. setState('pedding');

  409. // 重置文件总个数和总大小

  410. fileCount = 0;

  411. fileSize = 0;

  412. // 重置uploader,目前只重置了文件队列

  413. uploader.reset();

  414. // 更新状态等,重新计算文件总个数和总大小

  415. updateStatus();

  416. }

  417.  
  418. function setState( val ) {

  419. var file, stats;

  420. if ( val === state ) {

  421. return;

  422. }

  423. $upload.removeClass( 'state-' + state );

  424. $upload.addClass( 'state-' + val );

  425. state = val;

  426. switch (state) {

  427. case 'pedding':

  428. $placeHolder.removeClass( 'element-invisible' );

  429. $queue.hide();

  430. $statusBar.addClass( 'element-invisible' );

  431. uploader.refresh();

  432. break;

  433.  
  434. case 'ready':

  435. $placeHolder.addClass( 'element-invisible' );

  436. $( '#filePicker2' ).removeClass( 'element-invisible');

  437. $queue.show();

  438. $statusBar.removeClass('element-invisible');

  439. uploader.refresh();

  440. break;

  441.  
  442. case 'uploading':

  443. $( '#filePicker2' ).addClass( 'element-invisible' );

  444. $progress.show();

  445. $upload.text( '<s:text name="resource.pauseupload"></s:text>' );

  446. var fileArray1 = uploader.getFiles();

  447. var fileNames = [];

  448. fileSize = 0;

  449. for(var i=0; i<fileArray1.length; i++) {

  450. fileNames.push(fileArray1[i].name);

  451. fileSize += fileArray1[i].size;

  452. filePerSize.push(fileArray1[i].size);

  453. fileName.push(fileArray1[i].name);

  454. }

  455. $.extend(true, uploader.options.formData, {"fileSize": fileSize, "multiFileName": fileName, "filePerSize": filePerSize});

  456. break;

  457.  
  458. case 'paused':

  459. $progress.show();

  460. $upload.text('<s:text name="resource.continueupload"></s:text>');

  461. break;

  462.  
  463. case 'confirm':

  464. $progress.hide();

  465. $('#filePicker2').removeClass('element-invisible');

  466. $upload.text('<s:text name="resource.starttoupload"></s:text>');

  467.  
  468. stats = uploader.getStats();

  469. if (stats.successNum && !stats.uploadFailNum) {

  470. setState('finish');

  471. return;

  472. }

  473. break;

  474. case 'finish':

  475. stats = uploader.getStats();

  476. //alert(stats.successNum);

  477. if (stats.successNum) {

  478. if(flag) {

  479. //alert('上传成功');

  480. confirmBox("<s:text name='resource.tiptitle'></s:text>",

  481. "Upload Success",

  482. function(tag) {

  483. if (tag) {

  484. var url = 'resource/uploadHd.jsp';

  485. loadUrl(url);

  486. } else {

  487. return;

  488. }

  489. });

  490. $("#boxwhite a[name=f]").html("<s:text name="box.no"/>").hide();

  491. $("#boxwhite a[name=t]").html("<s:text name="box.sure"/>");

  492. } else {

  493. loadUrl('resource/uploadHd.jsp');

  494. }

  495. //刷新界面

  496. //setTimeout("loadUrl('resource/uploadHd.jsp')", 1000);

  497. } else {

  498. // 没有成功的图片,重设

  499. state = 'done';

  500. location.reload();

  501. }

  502. break;

  503. }

  504. updateStatus();

  505. }

  506.  
  507. var flag = true;

  508.  
  509. uploader.on("uploadAccept", function(object, ret){

  510. if(ret != null && ret != '') {

  511. var data = JSON.parse(ret._raw);

  512. if(data != null && data != '') {

  513. if(data.resultCode == '1' || data.resultCode == '2') {

  514. var tip = '';

  515. if(data.resultCode == '1') {

  516. tip = "<s:text name='resource.fileExists'></s:text>";

  517. }else {

  518. tip = "<s:text name='resource.fileTypeError'></s:text>" + data.message;

  519. }

  520. confirmBox("<s:text name='resource.tiptitle'></s:text>",

  521. tip,

  522. function(tag) {

  523. if (tag) {

  524. flag = false;

  525. updateStatus();

  526. var url = 'resource/uploadHd.jsp';

  527. loadUrl(url);

  528. } else {

  529. return;

  530. }

  531. });

  532. $("#boxwhite a[name=f]").html("<s:text name="box.no"/>").hide();

  533. $("#boxwhite a[name=t]").html("<s:text name="box.sure"/>");

  534. } else {

  535. flag = true;

  536. }

  537. }

  538. }

  539. });

  540.  
  541. uploader.onUploadProgress = function(file, percentage) {

  542. var $li = $('#'+file.id),

  543. $percent = $li.find('.progress span');

  544.  
  545. $percent.css( 'width', percentage * 100 + '%' );

  546. percentages[ file.id ][ 1 ] = percentage;

  547. updateTotalProgress();

  548. };

  549.  
  550. uploader.on("uploadError", function(file, reason){

  551. alert("uploadError");

  552. });

  553.  
  554. uploader.onFileQueued = function(file) {

  555. fileCount++;

  556. fileSize += file.size;

  557. if (fileCount === 1) {

  558. $placeHolder.addClass('element-invisible');

  559. $statusBar.show();

  560. }

  561.  
  562. addFile(file);

  563. setState('ready');

  564. updateTotalProgress();

  565. };

  566.  
  567. /**

  568. * 移出队列

  569. */

  570. uploader.onFileDequeued = function( file ) {

  571. fileCount--;

  572. fileSize -= file.size;

  573. if ( !fileCount ) {

  574. setState('pedding');

  575. }

  576. removeFile(file);

  577. updateTotalProgress();

  578. };

  579.  
  580. uploader.on('all', function(type) {

  581. var stats;

  582. switch(type) {

  583. case 'uploadFinished':

  584. setState('confirm');

  585. break;

  586.  
  587. case 'startUpload':

  588. setState('uploading');

  589. break;

  590.  
  591. case 'stopUpload':

  592. setState('paused');

  593. break;

  594. }

  595. });

  596.  
  597.  
  598. uploader.onError = function( code ) {

  599. if (type=="Q_TYPE_DENIED"){

  600. //dialogMsg("myModal","messageP","请上传JPG、PNG格式文件");

  601. }else if(type=="F_EXCEED_SIZE"){

  602. //dialogMsg("myModal","messageP","文件大小不能超过8M");

  603. }

  604. uploader.reset();

  605. fileSize = 0;

  606. fileName = [];

  607. filePerSize = [];

  608. };

  609.  
  610. /**

  611. * 点击上传按钮

  612. */

  613. $upload.on('click', function() {

  614. if ( $(this).hasClass( 'disabled' ) ) {

  615. return false;

  616. }

  617. if (state === 'ready') {

  618. uploader.upload();

  619. } else if (state === 'paused') {

  620. uploader.upload();

  621. } else if (state === 'uploading') {

  622. uploader.stop();

  623. }

  624. });

  625.  
  626. /**

  627. * 点击重试按钮

  628. */

  629. $info.on( 'click', '.retry', function() {

  630. uploader.retry();

  631. } );

  632.  
  633. /**

  634. * 点击忽略按钮

  635. */

  636. $info.on( 'click', '.ignore', function() {

  637. //执行忽略动作,把图片清除

  638. closeUploader();

  639. });

  640.  
  641. $upload.addClass( 'state-' + state );

  642. updateTotalProgress();

  643. });

  644. })( jQuery );

  •  

使用Action接收时,可以这么写:

 
  1. //多文件上传的文件对象,多文件是一个一个文件上传,所以multiFile是当前正在上传的文件对象

  2. private File multiFile;

  3. //多文件上传文件对象的名称,当前正在上传的文件名

  4. private String multiFileFileName;

  5. //所有文件的总大小

  6. private String fileSize;

  7. //文件名列表

  8. private String[] multiFileName;

  9. //每个文件的大小

  10. private String[] filePerSize;

  11. public void setMultiFile(File multiFile) {

  12. this.multiFile = multiFile;

  13. }

  14.  
  15. public File getMultiFile() {

  16. return multiFile;

  17. }

  18.  
  19. public void setMultiFileFileName(String multiFileFileName) {

  20. this.multiFileFileName = multiFileFileName;

  21. }

  22.  
  23. public void setFileSize(String fileSize) {

  24. this.fileSize = fileSize;

  25. }

  26.  
  27. public void setMultiFileName(String[] multiFileName) {

  28. this.multiFileName = multiFileName;

  29. }

  30.  
  31. public void setFilePerSize(String[] filePerSize) {

  32. this.filePerSize = filePerSize;

  33. }

  34. public void uploadFile() {

  35. String physicPath = Constant.AD_RESOURCE_BASE_DIR;

  36. String subPath = "";

  37. int resolution = -1;

  38. String type = request.getParameter("resourcetype");

  39. if(StringUtils.isNotBlank(type)) {

  40. if(Constant.RESOURCE_TYPE_HD.equals(type)) {

  41. subPath = Constant.AD_RESOURCE_HD_DIR;

  42. resolution = 1;

  43. } else if(Constant.RESOURCE_TYPE_SD.equals(type)) {

  44. subPath = Constant.AD_RESOURCE_SD_DIR;

  45. resolution = 0;

  46. }

  47. }

  48. File fdir = new File(physicPath+"/"+subPath);

  49. if(!fdir.exists()) {

  50. fdir.mkdirs();

  51. }

  52. String resPath = "/" + subPath + "/" + multiFileFileName;

  53. String path = physicPath + resPath;//文件路径

  54. PrintWriter out = null;

  55. try {

  56. out = response.getWriter();

  57. } catch (IOException e) {

  58. log.error(e);

  59. }

  60. if(!isValidResource(multiFileFileName.substring(multiFileFileName.lastIndexOf(".") + 1))) {

  61. ResultJson resultJson = new ResultJson();

  62. resultJson.setResultCode("2");

  63. resultJson.setMessage(multiFileFileName);

  64. out.print(JsonUtil.toJsonString(resultJson));

  65. return;

  66. }

  67. try {

  68. File file = this.getMultiFile();

  69. //判断文件是否已经存在,不存在则存,否则不存

  70. String savePath = path.substring(path.lastIndexOf("/" + Constant.AD_RESOURCE_STORE_BASE_DIR));

  71. boolean isExists = adResourceService.queryFile(savePath);//linux下图片名区分大小写

  72. log.info("isExist=" + isExists);

  73. if(isExists) {

  74. ResultJson resultJson = new ResultJson();

  75. resultJson.setResultCode("1");

  76. resultJson.setMessage("same name file exists!");

  77. response.getWriter().print(JsonUtil.toJsonString(resultJson));

  78. return;

  79. } else {

  80. ResultJson resultJson = new ResultJson();

  81. resultJson.setResultCode("0");

  82. resultJson.setMessage("ok");

  83. response.getWriter().print(JsonUtil.toJsonString(resultJson));

  84. }

  85. FileUtil.randomAccessFile(path, file);

  86. log.info("upload finish....");

  87. //insert into db.

  88. File f = new File(path);

  89. //1:bmp;2:jpg;3:gif;4:png;5:mpg;6:m2v

  90. log.info("f.exists()=" + f.exists());

  91. if(f.exists()) {

  92. String fname = f.getName();

  93. log.info("filename=" + fname);

  94. String fsuffix = fname.substring(fname.lastIndexOf(".") + 1);

  95. if(fname.endsWith(".bmp") || fname.endsWith(".BMP") || fname.endsWith(".jpg") || fname.endsWith(".JPG")

  96. || fname.endsWith(".gif") || fname.endsWith(".GIF") || fname.endsWith(".png") || fname.endsWith(".PNG")) {

  97.  
  98. BufferedImage bimg = ImageIO.read(f);

  99. int picWidth = bimg.getWidth();

  100. int picHeight = bimg.getHeight();

  101. int picType = 0;

  102. switch (fsuffix.toLowerCase()) {

  103. case Constant.IMG_FORMAT_BMP:

  104. picType = 1;

  105. break;

  106. case Constant.IMG_FORMAT_JPG:

  107. picType = 2;

  108. break;

  109. case Constant.IMG_FORMAT_PNG:

  110. picType = 4;

  111. break;

  112. case Constant.IMG_FORMAT_GIF:

  113. picType = 3;

  114. break;

  115. }

  116. System.out.println("fileSize=" + file.length());

  117. log.info("fileSize=" + file.length());

  118. adResourceService.upload(resolution, resPath, picHeight, picWidth, (int)file.length(), picType, fsuffix);

  119. } else if(fname.endsWith(".mpg") || fname.endsWith(".MPG") || fname.endsWith(".m2v") || fname.endsWith(".M2V")) {

  120. //截取画像,获取分辨率

  121. //mpg , m2v,直接把文件路径存进去,在预览的时候动态生成帧画面

  122. int picType = 0;

  123. if(fname.endsWith(".mpg") || fname.endsWith(".MPG")) {

  124. picType = 5;

  125. } else if(fname.endsWith(".m2v") || fname.endsWith(".M2V")) {

  126. picType = 6;

  127. }

  128.  
  129. boolean b = FFmpegUtil.transfer(path, path+".jpg");//在文件名后直接加后缀,然后存到数据库中

  130. if(b) {

  131. File snapFile = new File(path+".jpg");

  132. BufferedImage bimg = ImageIO.read(snapFile);

  133. int picWidth = bimg.getWidth();

  134. int picHeight = bimg.getHeight();

  135. //update db.

  136. adResourceService.uploadVideo(resolution, resPath, picHeight, picWidth, (int)file.length(), picType, fsuffix, resPath+".jpg");

  137. } else {

  138. log.error("generate snapshot file failed from " + path);

  139. }

  140. } else {

  141. log.error("file type invalid, we delete it...");

  142. f.delete();

  143. }

  144. }

  145. } catch (IOException e) {

  146. e.printStackTrace();

  147. log.error(e);

  148. }

  149. }

实际场景中可以根据自己的需要进行修改。