600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > webuploader 实现图片批量上传

webuploader 实现图片批量上传

时间:2021-10-24 05:35:41

相关推荐

webuploader 实现图片批量上传

1、导入资源

2、JSP代码

1<div class="page-container"> 2 <div class="row cl"> 3 <label class="form-label col-xs-4 col-sm-2"><span 4 class="c-red">*</span>项目名称:</label> 5 <div class="formControls col-xs-8 col-sm-9"> 6 <input type="text" class="input-text" value="${proName }" 7 placeholder="" id="" name="proName" readonly="readonly"> 8 </div> 9 </div>10 <div class="row cl">11 <label class="form-label col-xs-4 col-sm-2">缩略图:</label>12 <div class="formControls col-xs-8 col-sm-9">13 <div class="uploader-thum-container">14 <div id="fileList" class="uploader-list"></div>15 <div id="filePicker">选择图片</div>16 <button id="btn-star"17class="btn btn-default btn-uploadstar radius ml-10">开始上传</button>18 </div>19 </div>20 </div>21 <div class="row cl">22 <label class="form-label col-xs-4 col-sm-2"><span23 class="c-red">*</span>项目发票上传:</label>24 <div class="formControls col-xs-8 col-sm-9">25 <div class="uploader-list-container">26 <div class="queueList">27<div id="dndArea" class="placeholder">28 <div id="filePicker-2"></div>29 <p>或将照片拖到这里,单次最多可选300张</p>30</div>31 </div>32 <div class="statusBar" style="display:none;">33<div class="progress">34 <span class="text">0%</span> <span class="percentage"></span>35</div>36<div class="info"></div>37<div class="btns">38 <div id="filePicker2"></div>39 <div class="uploadBtn">开始上传</div>40</div>41 </div>42 </div>43 </div>44 </div>45 <div class="row cl">46 <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">47 <button48 onClick="article_add('','invoiceVo/save?&projectId=${projectId}&invoiceScan=','10001');"49 class="btn btn-primary radius" type="button">50 <i class="Hui-iconfont">&#xe632;</i> &nbsp;&nbsp;保存&nbsp;&nbsp;51 </button>52 </div>53 </div>54</div>

3、Js代码

1 <script type="text/javascript"> 2var imagePath=null; 3 4 function article_save() { 5 alert("刷新父级的时候会自动关闭弹层。"); 6 window.parent.location.reload(); 7 } 8 9 /*项目发票-添加*/ 10 function article_add(title, url, w, h) { 11 if(imagePath){ 12 var index = layer.open({ 13 type : 2, 14 title : title, 15 content : url+imagePath 16 }); 17 layer.full(index); 18 }else{alert("没有上传图片,请先上传图片");} 19 } $(function() { 22 $('.skin-minimal input').iCheck({ 23 checkboxClass : 'icheckbox-blue', 24 radioClass : 'iradio-blue', 25 increaseArea : '20%' 26 }); 27 28 $list = $("#fileList"), $btn = $("#btn-star"), state = "pending", 29 uploader; 30 31 var uploader = WebUploader.create({ 32 auto : true, 33 swf : 'lib/webuploader/0.1.5/Uploader.swf',// swf文件路径 34 35 // 文件接收服务端。 36 server : 'lib/webuploader/0.1.5/server/fileupload.php', // 文件接收服务端。 37 38 // 选择文件的按钮。可选。 39 // 内部根据当前运行是创建,可能是input元素,也可能是flash. 40 pick : '#filePicker', 41 42 // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传! 43 resize : false, 44 // 只允许选择图片文件。 45 accept : { 46 title : 'Images', 47 extensions : 'gif,jpg,jpeg,bmp,png', 48 mimeTypes : 'image/*' 49 } 50 }); 51 // 当有文件被添加进队列的时候 52 uploader 53 .on( 54 'fileQueued', 55 function(file) { 56 var $li = $('<div id="' + file.id + '" class="item">' 57 + '<div class="pic-box"><img></div>' 58 + '<div class="info">' 59 + file.name 60 + '</div>' 61 + '<p class="state">等待上传...</p>' 62 + '</div>'), $img = $li.find('img'); 63 $list.append($li); 64 65 // 创建缩略图 66 // 如果为非图片文件,可以不用调用此方法。 67 // thumbnailWidth x thumbnailHeight 为 100 x 100 68 uploader.makeThumb(file, function(error, src) { 69 if (error) { 70 $img.replaceWith('<span>不能预览</span>'); 71 return; 72 } 73 74 $img.attr('src', src); 75 }, thumbnailWidth, thumbnailHeight); 76 }); 77 // 文件上传过程中创建进度条实时显示。 78 uploader 79 .on( 80 'uploadProgress', 81 function(file, percentage) { 82 var $li = $('#' + file.id), $percent = $li 83 .find('.progress-box .sr-only'); 84 85 // 避免重复创建 86 if (!$percent.length) { 87 $percent = $( 88'<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>') 89.appendTo($li).find('.sr-only'); 90 } 91 $li.find(".state").text("上传中"); 92 $percent.css('width', percentage * 100 + '%'); 93 }); 94 95 // 文件上传成功,给item添加成功class, 用样式标记上传成功。 96 uploader.on('uploadSuccess', function(file) { 97 $('#' + file.id).addClass('upload-state-success') 98.find(".state").text("已上传"); 99 });100 101 // 文件上传失败,显示上传出错。102 uploader.on('uploadError', function(file) {103 $('#' + file.id).addClass('upload-state-error').find(".state")104.text("上传出错");105 });106 107 // 完成上传完了,成功或者失败,先删除进度条。108 uploader.on('uploadComplete', function(file) {109 $('#' + file.id).find('.progress-box').fadeOut();110 });111 uploader.on('all', function(type) {112 if (type === 'startUpload') {113 state = 'uploading';114 } else if (type === 'stopUpload') {115 state = 'paused';116 } else if (type === 'uploadFinished') {117 state = 'done';118 }119 120 if (state === 'uploading') {121 $btn.text('暂停上传');122 } else {123 $btn.text('开始上传');124 }125 });126 127 $btn.on('click', function() {128 if (state === 'uploading') {129 uploader.stop();130 } else {131 uploader.upload();132 }133 });134 135 });136 137 (function($) {138 // 当domReady的时候开始初始化139 $(function() {140 var $wrap = $('.uploader-list-container'),141 142 // 图片容器143 $queue = $('<ul class="filelist"></ul>').appendTo(144$wrap.find('.queueList')),145 146 // 状态栏,包括进度和控制按钮147 $statusBar = $wrap.find('.statusBar'),148 149 // 文件总体选择信息。150 $info = $statusBar.find('.info'),151 152 // 上传按钮153 $upload = $wrap.find('.uploadBtn'),154 155 // 没选择文件之前的内容。156 $placeHolder = $wrap.find('.placeholder'),157 158 $progress = $statusBar.find('.progress').hide(),159 160 // 添加的文件数量161 fileCount = 0,162 163 // 添加的文件总大小164 fileSize = 0,165 166 // 优化retina, 在retina下这个值是2167 ratio = window.devicePixelRatio || 1,168 169 // 缩略图大小170 thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio,171 172 // 可能有pedding, ready, uploading, confirm, done.173 state = 'pedding',174 175 // 所有文件的进度信息,key为file id176 percentages = {},177 // 判断浏览器是否支持图片的base64178 isSupportBase64 = (function() {179 var data = new Image();180 var support = true;181 data.onload = data.onerror = function() {182if (this.width != 1 || this.height != 1) {183 support = false;184}185 }186 data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";187 return support;188 })(),189 190 // 检测是否已经安装flash,检测flash的版本191 flashVersion = (function() {192 var version;193 194 try {195version = navigator.plugins['Shockwave Flash'];196version = version.description;197 } catch (ex) {198try {199 version = new ActiveXObject(200 'ShockwaveFlash.ShockwaveFlash')201 .GetVariable('$version');202} catch (ex2) {203 version = '0.0';204}205 }206 version = version.match(/\d+/g);207 return parseFloat(version[0] + '.' + version[1], 10);208 })(),209 210 supportTransition = (function() {211 var s = document.createElement('p').style, r = 'transition' in s212 || 'WebkitTransition' in s213 || 'MozTransition' in s214 || 'msTransition' in s || 'OTransition' in s;215 s = null;216 return r;217 })(),218 219 // WebUploader实例220 uploader;221 222 if (!WebUploader.Uploader.support('flash')223&& WebUploader.browser.ie) {224 225 // flash 安装了但是版本过低。226 if (flashVersion) {227(function(container) {228 window['expressinstallcallback'] = function(state) {229 switch (state) {230 case 'Download.Cancelled':231 alert('您取消了更新!')232 break;233 234 case 'Download.Failed':235 alert('安装失败')236 break;237 238 default:239 alert('安装已成功,请刷新!');240 break;241 }242 delete window['expressinstallcallback'];243 };244 245 var swf = 'expressInstall.swf';246 // insert flash object247 var html = '<object type="application/'248 + 'x-shockwave-flash" data="' + swf + '" ';249 250 if (WebUploader.browser.ie) {251 html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';252 }253 254 html += 'width="100%" height="100%" style="outline:0">'255 + '<param name="movie" value="' + swf + '" />'256 + '<param name="wmode" value="transparent" />'257 + '<param name="allowscriptaccess" value="always" />'258 + '</object>';259 260 container.html(html);261 262})($wrap);263 264// 压根就没有安转。265 } else {266$wrap267 .html('<a href="/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');268 }269 270 return;271 } else if (!WebUploader.Uploader.support()) {272 alert('Web Uploader 不支持您的浏览器!');273 return;274 }275 276 // 实例化277 uploader = WebUploader.create({278 pick : {279id : '#filePicker-2',280label : '点击选择图片'281 },282 formData : {283uid : 123284 },285 dnd : '#dndArea',286 paste : '#uploader',287 swf : 'lib/webuploader/0.1.5/Uploader.swf',288 chunked : false,289 chunkSize : 512 * 1024,290 server : 'invoiceVo/news_uploder?&projectId=${projectId}',291 // runtimeOrder: 'flash',292 293 // accept: {294 //title: 'Images',295 //extensions: 'gif,jpg,jpeg,bmp,png',296 //mimeTypes: 'image/*'297 // },298 299 // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。300 disableGlobalDnd : true,301 fileNumLimit : 300,302 fileSizeLimit : 200 * 1024 * 1024, // 200 M303 fileSingleSizeLimit : 50 * 1024 * 1024304 // 50 M305 });306 307 // 拖拽时不接受 js, txt 文件。308 uploader.on('dndAccept', function(items) {309 var denied = false, len = items.length, i = 0,310 // 修改js类型311 unAllowed = 'text/plain;application/javascript ';312 313 for (; i < len; i++) {314// 如果在列表里面315if (~unAllowed.indexOf(items[i].type)) {316 denied = true;317 break;318}319 }320 321 return !denied;322 });323 324 uploader.on('dialogOpen', function() {325 console.log('here');326 });327 328 // uploader.on('filesQueued', function() {329 //uploader.sort(function( a, b ) {330 // if ( a.name < b.name )331 // return -1;332 // if ( a.name > b.name )333 // return 1;334 // return 0;335 //});336 // });337 338 // 添加“添加文件”的按钮,339 /* uploader.addButton({340 id : '#filePicker2',341 label : '继续添加'342 }); */343 344 uploader.on('ready', function() {345 window.uploader = uploader;346 });347 348 // 当有文件添加进来时执行,负责view的创建349 function addFile(file) {350 var $li = $('<li id="' + file.id + '">'351 + '<p class="title">' + file.name + '</p>'352 + '<p class="imgWrap"></p>'353 + '<p class="progress"><span></span></p>' + '</li>'),354 355 $btns = $(356 '<div class="file-panel">'357 + '<span class="cancel">删除</span>'358 + '<span class="rotateRight">向右旋转</span>'359 + '<span class="rotateLeft">向左旋转</span></div>')360 .appendTo($li), $prgress = $li361 .find('p.progress span'), $wrap = $li362 .find('p.imgWrap'), $info = $('<p class="error"></p>'),363 364 showError = function(code) {365switch (code) {366case 'exceed_size':367 text = '文件大小超出';368 break;369 370case 'interrupt':371 text = '上传暂停';372 break;373 374default:375 text = '上传失败,请重试';376 break;377}378 379$info.text(text).appendTo($li);380 };381 382 if (file.getStatus() === 'invalid') {383showError(file.statusText);384 } else {385// @todo lazyload386$wrap.text('预览中');387uploader388 .makeThumb(389 file,390 function(error, src) {391var img;392 393if (error) {394 $wrap.text('不能预览');395 return;396}397 398if (isSupportBase64) {399 img = $('<img src="'+src+'">');400 $wrap.empty().append(img);401} else {402 $403 .ajax(404'lib/webuploader/0.1.5/server/preview.php',405{406 method : 'POST',407 data : src,408 dataType : 'json'409})410 .done(411function(412 response) {413 if (response.result) {414 img = $('<img src="'+response.result+'">');415 $wrap416 .empty()417 .append(418 img);419 } else {420 $wrap421 .text("预览出错");422 }423});424}425 }, thumbnailWidth, thumbnailHeight);426 427percentages[file.id] = [ file.size, 0 ];428file.rotation = 0;429 }430 431 file.on('statuschange', function(cur, prev) {432if (prev === 'progress') {433 $prgress.hide().width(0);434} else if (prev === 'queued') {435 $li.off('mouseenter mouseleave');436 $btns.remove();437}438 439// 成功440if (cur === 'error' || cur === 'invalid') {441 console.log(file.statusText);442 showError(file.statusText);443 percentages[file.id][1] = 1;444} else if (cur === 'interrupt') {445 showError('interrupt');446} else if (cur === 'queued') {447 percentages[file.id][1] = 0;448} else if (cur === 'progress') {449 $info.remove();450 $prgress.css('display', 'block');451} else if (cur === 'complete') {452 $li.append('<span class="success"></span>');453}454 455$li.removeClass('state-' + prev).addClass(456 'state-' + cur);457 });458 459 $li.on('mouseenter', function() {460$btns.stop().animate({461 height : 30462});463 });464 465 $li.on('mouseleave', function() {466$btns.stop().animate({467 height : 0468});469 });470 471 $btns472 .on(473 'click',474 'span',475 function() {476 var index = $(this).index(), deg;477 478 switch (index) {479 case 0:480uploader.removeFile(file);481return;482 483 case 1:484file.rotation += 90;485break;486 487 case 2:488file.rotation -= 90;489break;490 }491 492 if (supportTransition) {493deg = 'rotate(' + file.rotation494 + 'deg)';495$wrap.css({496 '-webkit-transform' : deg,497 '-mos-transform' : deg,498 '-o-transform' : deg,499 'transform' : deg500});501 } else {502$wrap503 .css(504 'filter',505 'progid:DXImageTransform.Microsoft.BasicImage(rotation='506 + (~~((file.rotation / 90) % 4 + 4) % 4)507 + ')');508 509 }510 511 });512 513 $li.appendTo($queue);514 }515 516 // 负责view的销毁517 function removeFile(file) {518 var $li = $('#' + file.id);519 520 delete percentages[file.id];521 updateTotalProgress();522 $li.off().find('.file-panel').off().end().remove();523 }524 525 function updateTotalProgress() {526 var loaded = 0, total = 0, spans = $progress.children(), percent;527 528 $.each(percentages, function(k, v) {529total += v[0];530loaded += v[0] * v[1];531 });532 533 percent = total ? loaded / total : 0;534 535 spans.eq(0).text(Math.round(percent * 100) + '%');536 spans.eq(1).css('width', Math.round(percent * 100) + '%');537 updateStatus();538 }539 540 function updateStatus() {541 var text = '', stats;542 543 if (state === 'ready') {544text = '选中' + fileCount + '张图片,共'545 + WebUploader.formatSize(fileSize) + '。';546 } else if (state === 'confirm') {547stats = uploader.getStats();548if (stats.uploadFailNum) {549 text = '已成功上传'550 + stats.successNum551 + '张照片至XX相册,'552 + stats.uploadFailNum553 + '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'554}555 556 } else {557stats = uploader.getStats();558text = '共' + fileCount + '张('559 + WebUploader.formatSize(fileSize) + '),已上传'560 + stats.successNum + '张';561 562if (stats.uploadFailNum) {563 text += ',失败' + stats.uploadFailNum + '张';564}565 }566 567 $info.html(text);568 }569 570 function setState(val) {571 var file, stats;572 573 if (val === state) {574return;575 }576 577 $upload.removeClass('state-' + state);578 $upload.addClass('state-' + val);579 state = val;580 581 switch (state) {582 case 'pedding':583$placeHolder.removeClass('element-invisible');584$queue.hide();585$statusBar.addClass('element-invisible');586uploader.refresh();587break;588 589 case 'ready':590$placeHolder.addClass('element-invisible');591$('#filePicker2').removeClass('element-invisible');592$queue.show();593$statusBar.removeClass('element-invisible');594uploader.refresh();595break;596 597 case 'uploading':598$('#filePicker2').addClass('element-invisible');599$progress.show();600$upload.text('暂停上传');601break;602 603 case 'paused':604$progress.show();605$upload.text('继续上传');606break;607 608 case 'confirm':609$progress.hide();610$('#filePicker2').removeClass('element-invisible');611$upload.text('开始上传');612 613stats = uploader.getStats();614if (stats.successNum && !stats.uploadFailNum) {615 setState('finish');616 return;617}618break;619 case 'finish':620stats = uploader.getStats();621if (stats.successNum) {622 alert('上传成功');623 624} else {625 // 没有成功的图片,重设626 state = 'done';627 location.reload();628}629break;630 }631 632 updateStatus();633 }634 635 uploader.onUploadProgress = function(file, percentage) {636 var $li = $('#' + file.id), $percent = $li637 .find('.progress span');638 639 $percent.css('width', percentage * 100 + '%');640 percentages[file.id][1] = percentage;641 updateTotalProgress();642 };643 644 uploader.onFileQueued = function(file) {645 fileCount++;646 fileSize += file.size;647 648 if (fileCount === 1) {649$placeHolder.addClass('element-invisible');650$statusBar.show();651 }652 653 addFile(file);654 setState('ready');655 updateTotalProgress();656 };657 658 uploader.onFileDequeued = function(file) {659 fileCount--;660 fileSize -= file.size;661 662 if (!fileCount) {663setState('pedding');664 }665 666 removeFile(file);667 updateTotalProgress();668 669 };670 671 /*获取服务器返回的数据*/672 uploader.on('uploadSuccess', function(file, response) {673 alert(response.status);674 if (response.status == "success") {675imagePath =response.filePath;676alert("文件保存路径:" + response.filePath);677 } else if (response.status == "error")678alert(response.error);679 });680 681 uploader.on('all', function(type) {682 var stats;683 //alert(type);684 switch (type) {685 case 'uploadFinished':686 687setState('confirm');688break;689 690 case 'startUpload':691setState('uploading');692break;693 694 case 'stopUpload':695setState('paused');696break;697 698 }699 });700 701 uploader.onError = function(code) {702 alert('Eroor: ' + code);703 };704 705 $upload.on('click', function() {706 if ($(this).hasClass('disabled')) {707return false;708 }709 710 if (state === 'ready') { //点击上传按钮,进入准备状态。711uploader.upload(); //开始上传712 } else if (state === 'paused') {713uploader.upload();714 } else if (state === 'uploading') {715uploader.stop();716 }717 });718 719 $info.on('click', '.retry', function() {720 uploader.retry();721 });722 723 $info.on('click', '.ignore', function() {724 alert('todo');725 });726 727 $upload.addClass('state-' + state);728 updateTotalProgress();729 });730 731 })(jQuery);732</script>

注意:

4、controller代码

12/** 3* 跳转到上传发票的页面 4* @param proName 5* @param map 6* @return 7*/ 8@RequestMapping(value = "/upload" ) 9public String invoiceUpload(String proName,Long id,Map<String, Object> map){10 map.put("proName", proName);11 projectService.getProject(id);12 map.put("projectId", id);13 return "project/invoiceUpload";14}15161718/**19* 上传发票并保存导数据库20* @param file21* @param request22* @param response23* @return24*/25@ResponseBody 26@RequestMapping(value = "/news_uploder", method ={RequestMethod.POST,RequestMethod.GET}, produces = "application/json; charset=utf-8")27public JSONObject uploder(@RequestParam MultipartFile[] file,Long projectId,HttpServletRequest request,HttpServletResponse response){ 28 String flag=null; 29 30 JSONObject jsonObject = new JSONObject();31 try { 32 WebuploaderUtil webuploaderUtil=new WebuploaderUtil(); 33 webuploaderUtil.upload(file[0], "upload/invoice/", request); 34 flag=webuploaderUtil.getFileName(); 35 jsonObject.put("filePath", flag);36 jsonObject.put("status", "success");37 38 } catch (Exception e) { 39 e.printStackTrace(); 40 }41 42 return jsonObject; 43} 4445

5、工具类

1 package com.softjx.util; 2 3 /** 4 *Project Name: QDLIMAP 5 *File Name: WebuploaderUtil.java 6 *Package Name: com.ltmap.platform.cms.util 7 *Date: 4月13日 下午6:30:45 8 *Copyright (c) ,578888218@ All Rights Reserved. 9 */ 1011 12 import java.io.File; 13 import java.text.SimpleDateFormat; 14 import java.util.Date; 15 16 import javax.servlet.http.HttpServletRequest; 17 18 import org.springframework.web.multipart.MultipartFile; 19 20 /** 21 *Title:WebuploaderUtil<br/> 22 *Description: 23 *@Company: 励图高科<br/> 24 *@author: 刘云生 25 *@version: v1.0 26 *@since:JDK 1.8.0_40 27 *@Date:4月13日 下午6:30:45 <br/> 28 */ 29 public class WebuploaderUtil { 30private String allowSuffix = "jpg,png,gif,jpeg";//允许文件格式 31private long allowSize = 2L;//允许文件大小 32private String fileName; 33private String[] fileNames; 34 35public String getAllowSuffix() { 36 return allowSuffix; 37} 38 39public void setAllowSuffix(String allowSuffix) { 40 this.allowSuffix = allowSuffix; 41} 42 43public long getAllowSize() { 44 return allowSize*1024*1024; 45} 46 47public void setAllowSize(long allowSize) { 48 this.allowSize = allowSize; 49} 50 51public String getFileName() { 52 return fileName; 53} 54 55public void setFileName(String fileName) { 56 this.fileName = fileName; 57} 58 59public String[] getFileNames() { 60 return fileNames; 61} 62 63public void setFileNames(String[] fileNames) { 64 this.fileNames = fileNames; 65} 66 67 68 69/** 70* 71* @Title: getFileNameNew72* @Description: TODO73* @param: @return 74* @return:String 75* @author:刘云生 76* @Date: 4月14日 上午10:17:3577* @throws 78*/ 79private String getFileNameNew(){ 80 SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 81 return fmt.format(new Date()); 82} 83 84 85/** 86* 87* @Title: uploads88* @Description: TODO89* @param: @param files 90* @param: @param destDir 91* @param: @param request 92* @param: @throws Exception 93* @return:void 94* @author:刘云生 95* @Date: 4月14日 上午10:17:1496* @throws 97*/ 98public void uploads(MultipartFile[] files, String destDir,HttpServletRequest request) throws Exception { 99 String path = request.getContextPath(); 100 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 101 try { 102 fileNames = new String[files.length]; 103 int index = 0; 104 for (MultipartFile file : files) { 105 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 106 int length = getAllowSuffix().indexOf(suffix); 107 if(length == -1){ 108 throw new Exception("请上传允许格式的文件"); 109 } 110 if(file.getSize() > getAllowSize()){ 111 throw new Exception("您上传的文件大小已经超出范围"); 112 } 113 String realPath = request.getSession().getServletContext().getRealPath("/"); 114 File destFile = new File(realPath+destDir); 115 if(!destFile.exists()){ 116 destFile.mkdirs(); 117 } 118 String fileNameNew = getFileNameNew()+"."+suffix;// 119 File f = new File(destFile.getAbsoluteFile()+"\\"+fileNameNew); 120 file.transferTo(f); 121 f.createNewFile(); 122 fileNames[index++] =basePath+destDir+fileNameNew; 123 } 124 } catch (Exception e) { 125 throw e; 126 } 127} 128 129 130/** 131* 132* @Title: upload 133* @Description: TODO 134* @param: @param file 135* @param: @param destDir 136* @param: @param request 137* @param: @throws Exception 138* @return:void 139* @author:刘云生 140* @Date: 4月14日 上午10:16:16141* @throws 142*/ 143public void upload(MultipartFile file, String destDir,HttpServletRequest request) throws Exception { 144 String path = request.getContextPath(); 145 //http://localhost:8088/huahang146 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; 147 try { 148 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 149 int length = getAllowSuffix().indexOf(suffix); 150 if(length == -1){ 151 throw new Exception("请上传允许格式的文件"); 152 } 153 if(file.getSize() > getAllowSize()){ 154 throw new Exception("您上传的文件大小已经超出范围"); 155 } 156 157 String realPath = request.getSession().getServletContext().getRealPath("/")+"/"; 158 159 File destFile = new File(realPath+destDir); 160 if(!destFile.exists()){ 161 destFile.mkdirs(); 162 } 163 String fileNameNew = getFileNameNew()+"."+suffix; 164 File f = new File(destFile.getAbsoluteFile()+"/"+fileNameNew); 165 file.transferTo(f); 166 f.createNewFile(); 167 //包含网站的全路径http://localhost:8080/QDLIMAP/upload/user/0414104142667.png 168 //fileName = basePath+destDir+fileNameNew; 169 //返回相对路径upload/user/0414104142667.png 170 fileName = destDir+fileNameNew; 171 } catch (Exception e) { 172 throw e; 173} 174 } 175 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。