webUpload组件实现文件上传功能和下载功能_webuploader 0.1.5-程序员宅基地

技术标签: java  javascript  

一、上传功能

首先引用基于jquery的百度上传组件webuploader(webuploader.css,webuploader.js)(jquery版本要求>1.10,webuploader版本:0.1.5),下载链接:http://www.jq22.com/jquery-info2665

<link rel="stylesheet" type="text/css" href="webuploader.css"/>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="webuploader.js"></script>

创建初始化方法,初始化webuploader插件对象(可以写在一个js文件中,外部js文件引用即可)

//初始化方法
//id:上传文件关联数据id(可选),successCallBack:外部调用的上传函数,fileType:文件类型
function initUpload(id,successCallBack){
	var fileType;
	var dhtml = '';
		dhtml += '<div>';
		dhtml += '<table id="file-list" class="table table-bordered"><tr><th width="130px">文件名称</th><th>文件大小</th><th>上传进度</th></tr></table>';
		dhtml += '<div class="btn btn-primary" id="select-file">选择文件</div><div style="margin-left:10px" class="btn btn-primary" id="start-upload">开始上传</div>';
		dhtml += '</div>';
		//点击上传跳出的弹窗
		var d = dialog({
			title: '文件上传',
			width: 360,
			//加载标签
			content: dhtml
		})
		//显示弹窗
		d.showModal();
    //创建并初始化WebUploader对象
 	var fileUploader = WebUploader.create({
  	    // swf文件路径(引用下载的webuploader的压缩包里的swf文件)
  	    swf: 'Uploader.swf',
  	    //是否允许重复的图片
  	  	duplicate :true,
  	  	// 选完文件后,是否自动上传
  	    auto: false,
  	    // 文件上传的服务器地址。
  	    server: "UploadServlet",
  	    // 选择文件的按钮。可选。
  	    // 内部根据当前运行是创建,可能是input元素,也可能是flash.
  	    pick: '#select-file',
  	    // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
  	    resize: false,
  	    //上传文件类型
  	    accept: fileType || null,
  	    /*//线程数
        threads: 1,
        //单个文件大小限制
        fileSingleSizeLimit: 2000,
        //上传文件数量限制
        fileNumLimit:10,
        //上传前不压缩
        compress:false,*/
  	});
  	//监听WebUploader事件:
  	//当有一批文件加载进队列时触发事件
  	fileUploader.on( 'fileQueued', function( file ) {
  		var html = '';
  		var attachmentSize = WebUploader.formatSize(file.size);
  		html += '<tr id="' + file.id +'"><td>' +file.name+'<b></b></td><td>'+attachmentSize+'</td><td><div class="progress" style="margin-bottom:0"><div class="progress-bar" style="width: 0%"></div></div></td></tr>';
		$(html).appendTo('#file-list');
  	});
  	// 文件上传过程中创建进度条实时显示。
  	fileUploader.on( 'uploadProgress', function( file, percentage ) {
  		$("#"+file.id).find('b').html('<span>' + percentage*100 + '%</span>');
		$('#'+file.id+' .progress').find(".progress-bar").css('width',percentage*100 + '%');//控制进度条
  	});
  	// 文件开始上传时执行。
  	fileUploader.on( 'uploadStart', function( file ) {
  	    
  	});
  	// 文件上传成功时执行。
  	fileUploader.on( 'uploadSuccess', function(file,response) {
  		var filePath = response.id;
  		if(response.error == 0){
  	  		successCallBack(file,filePath);
  		}else{
  			alert(response.message,3);
  		}
  	});
  	// 文件上传失败时执行。
  	fileUploader.on( 'uploadError', function( file ) {
  	    fileType = file.type;
  	});
  	//错误处理
  	fileUploader.on('error', function( code ) {
        var text = '';
        var message = '';
        if(fileType){
        	message = fileType.extensions
        }else{
        	message = "doc,docx"
        }
        switch( code ) {
          case  'F_DUPLICATE' : text = '该文件已经被选择了!' ;
          break;
          case  'Q_EXCEED_NUM_LIMIT' : text = '上传文件数量超过限制!' ;
          break;
          case  'Q_EXCEED_SIZE_LIMIT' : text = '所有文件总大小超过限制!';
          break;
          case 'Q_TYPE_DENIED' : text = '请上传'+'  '+message+'  '+'类型的文件';
          break;
          default : text = '未知错误!';
          break;  
        }
        alert(text,3);
      });
  	// 所有文件上传完成触发
  	fileUploader.on( 'uploadFinished', function( file ) {
  		d.remove();
  	});
  	
  	$("#start-upload").click(function(){
  		//调用WebUploader的upload()方法,开始上传此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  		//可以指定开始某一个文件。
  		fileUploader.upload();
  	})
}

未涉及的方法或参数请看官方文档:http://fex.baidu.com/webuploader/doc/index.html
3. HTML页面

<table border='1' id='theTable'>
	<tr>
		<th>id</td>
		<th>操作</td>
	</tr>
	<tr>
		<td>1</td>
		<td><a style="cursor:pointer;color:#337ab7;" id="upload" class="upload"/>上传</a></td>
	</tr>
</table>

页面上传函数

$('.upload').live("click", function() {
	var id = $(this).closest("tr").find("td").eq(0).text();
	initUpload(id,uploadFile);
});
//将上传的文件信息及上传路径传入后端,后端经过处理录入数据库
function uploadFile(file, filePath) {
    var fileName = file.name;
    $.ajax({
        url : "/service/serviceMethod/"+id+"/"+fileName+"/"+filePath,
        type : "POST",
        contentType : "application/json",
        data : JSON
        success: function(data){
            alert("附件上传成功",1);
            location.reload();
        },
        error : function() {
            alert("上传文件异常!",3);
        }
    });
}

二、下载功能

页面函数

function download(obj){
	var url= '';
	if(typeof(obj.filePath) != "undefined") {
		url = obj.filePath;
	} else if(typeof($(obj).attr("name")) != "undefined"){
		url = $(obj).attr("name");	
	}
	if(url == '') {
		return ;
	}
	if(url.indexOf("\\")>-1){
		url = url.replace(/\\/g,"/");
	}
	if (url.indexOf("upload/") >= 0 || url.indexOf("temp/") >= 0) {
		var url = "/downloadServlet?filePath=" + url;
		downloadContent(url);
	}else{
		alert("文件路径错误,下载失败",3);
	}
}

java后端downloadServlet代码

/**
 * 下载文件
 */
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
	//编码格式
	private String code = "utf-8";
	
	public DownloadServlet() {
		super();
	}

	public void init(ServletConfig config) throws ServletException {

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		InputStream  systemConfig= request.getServletContext().getResourceAsStream("/WEB-INF/classes/systemConfig.properties");
		Properties properties = new Properties();
		//加载properties文件
		properties.load(systemConfig);
		//文件下载后存放路径
		String fileSystemPath = pro.getProperty("fileSystemPath");
		//下载路径
		String filePath = request.getParameter("filePath");
		File file = new File(fileSystemPath + File.separator + filePath);
		/* 如果文件存在 */
		if (file.exists()) {
			//设置文件内容编码格式
			String fileName = URLEncoder.encode(file.getName(), code);
			//清除下载后文件首部的空白行
			response.reset();
			ServletContext servletContext=request.getServletContext();
			//使客户端浏览器通过MIME类型来处理json字符串
			response.setContentType(servletContext.getMimeType(fileName));  
			//附件下载
			response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
			int fileLength = (int) file.length();
			response.setContentLength(fileLength);
			/* 如果文件长度大于0 */
			if (fileLength > 0) {
				/* 创建输入流 */
				InputStream inStream = null;
				ServletOutputStream outStream = null;
				try {
					inStream = new FileInputStream(file);
					byte[] buf = new byte[4096];
					/* 创建输出流 */
					outStream = response.getOutputStream();
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						outStream.write(buf, 0, readLength);
					}
				} finally {
					inStream.close();
					outStream.flush();
					outStream.close();
				}
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

systemConfig.properties文件
fileSystemPath=D:/downLoadFile

参考文章:http://blog.ncmem.com/wordpress/2023/09/14/webupload%e7%bb%84%e4%bb%b6%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%8a%9f%e8%83%bd%e5%92%8c%e4%b8%8b%e8%bd%bd%e5%8a%9f%e8%83%bd/
欢迎入群一起讨论
在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45525177/article/details/132875935

智能推荐

机器学习模型评分总结(sklearn)_model.score-程序员宅基地

文章浏览阅读1.5w次,点赞10次,收藏129次。文章目录目录模型评估评价指标1.分类评价指标acc、recall、F1、混淆矩阵、分类综合报告1.准确率方式一:accuracy_score方式二:metrics2.召回率3.F1分数4.混淆矩阵5.分类报告6.kappa scoreROC1.ROC计算2.ROC曲线3.具体实例2.回归评价指标3.聚类评价指标1.Adjusted Rand index 调整兰德系数2.Mutual Informa..._model.score

Apache虚拟主机配置mod_jk_apache mod_jk 虚拟-程序员宅基地

文章浏览阅读344次。因工作需要,在Apache上使用,重新学习配置mod_jk1. 分别安装Apache和Tomcat:2. 编辑httpd-vhosts.conf: LoadModule jk_module modules/mod_jk.so #加载mod_jk模块 JkWorkersFile conf/workers.properties #添加worker信息 JkLogFil_apache mod_jk 虚拟

Android ConstraintLayout2.0 过度动画MotionLayout MotionScene3_android onoffsetchanged-程序员宅基地

文章浏览阅读335次。待老夫kotlin大成,扩展:MotionLayout 与 CoordinatorLayout,DrawerLayout,ViewPager 的 交互众所周知,MotionLayout 的 动画是有完成度的 即Progress ,他在0-1之间变化,一.CoordinatorLayout 与AppBarLayout 交互时,其实就是监听 offsetliner 这个 偏移量的变化 同样..._android onoffsetchanged

【转】多核处理器的工作原理及优缺点_多核处理器怎么工作-程序员宅基地

文章浏览阅读8.3k次,点赞3次,收藏19次。【转】多核处理器的工作原理及优缺点《处理器关于多核概念与区别 多核处理器工作原理及优缺点》原文传送门  摘要:目前关于处理器的单核、双核和多核已经得到了普遍的运用,今天我们主要说说关于多核处理器的一些相关概念,它的工作与那里以及优缺点而展开的分析。1、多核处理器  多核处理器是指在一枚处理器中集成两个或多个完整的计算引擎(内核),此时处理器能支持系统总线上的多个处理器,由总..._多核处理器怎么工作

个人小结---eclipse/myeclipse配置lombok_eclispe每次运行个新项目都需要重新配置lombok吗-程序员宅基地

文章浏览阅读306次。1. eclipse配置lombok 拷贝lombok.jar到eclipse.ini同级文件夹下,编辑eclipse.ini文件,添加: -javaagent:lombok.jar2. myeclipse配置lombok myeclipse像eclipse配置后,定义对象后,直接访问方法,可能会出现飘红的报错。 如果出现报错,可按照以下方式解决。 ..._eclispe每次运行个新项目都需要重新配置lombok吗

【最新实用版】Python批量将pdf文本提取并存储到txt文件中_python批量读取文字并批量保存-程序员宅基地

文章浏览阅读1.2w次,点赞31次,收藏126次。#注意:笔者在2021/11/11当天调试过这个代码是可用的,由于pdfminer版本的更新,网络上大多数的语法没有更新,我也是找了好久的文章才修正了我的代码,仅供学习参考。1、把pdf文件移动到本代码文件的同一个目录下,笔者是在pycharm里面运行的项目,下图中的x1文件夹存储了我需要转换成文本文件的所有pdf文件。然后要在此目录下创建一个存放转换后的txt文件的文件夹,如图中的txt文件夹。2、编写代码 (1)导入所需库# coding:utf-8import ..._python批量读取文字并批量保存

随便推点

Scala:访问修饰符、运算符和循环_scala ===运算符-程序员宅基地

文章浏览阅读1.4k次。http://blog.csdn.net/pipisorry/article/details/52902234Scala 访问修饰符Scala 访问修饰符基本和Java的一样,分别有:private,protected,public。如果没有指定访问修饰符符,默认情况下,Scala对象的访问级别都是 public。Scala 中的 private 限定符,比 Java 更严格,在嵌套类情况下,外层_scala ===运算符

MySQL导出ER图为图片或PDF_数据库怎么导出er图-程序员宅基地

文章浏览阅读2.6k次,点赞7次,收藏19次。ER图导出为PDF或图片格式_数据库怎么导出er图

oracle触发器修改同一张表,oracle触发器中对同一张表进行更新再查询时,需加自制事务...-程序员宅基地

文章浏览阅读655次。CREATE OR REPLACE TRIGGER Trg_ReimFactBEFORE UPDATEON BP_OrderFOR EACH ROWDECLAREPRAGMA AUTONOMOUS_TRANSACTION;--自制事务fc varchar2(255);BEGINIF ( :NEW.orderstate = 2AND :NEW.TransState = 1 ) THENBEG..._oracle触发器更新同一张表

debounce与throttle区别及其应用场景_throttle和debounce应用在哪些场景-程序员宅基地

文章浏览阅读513次。目录概念debouncethrottle实现debouncethrottle应用场景debouncethrottle场景举例debouncethrottle概念debounce字面理解是“防抖”,何谓“防抖”,就是连续操作结束后再执行,以网页滚动为例,debounce要等到用户停止滚动后才执行,将连续多次执行合并为一次执行。throttle字面理解是“节流”,何谓“节流”,就是确保一段时..._throttle和debounce应用在哪些场景

java操作mongdb【超详细】_java 操作mongodb-程序员宅基地

文章浏览阅读526次。regex() $regex 正则表达式用于模式匹配,基本上是用于文档中的发现字符串 (下面有例子)注意:若未加 @Field("名称") ,则识别mongdb集合中的key名为实体类属性名。也可以对数组进行索引,如果被索引的列是数组时,MongoDB会索引这个数组中的每一个元素。也可以对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。_java 操作mongodb

github push 推送代码失败. 使用ssh rsa key. remote: Support for password authentication was removed._git push remote: support for password authenticati-程序员宅基地

文章浏览阅读1k次。今天push代码到github仓库时出现这个报错TACKCHEN-MB0:tc-image tackchen$ git pushremote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.remote: Please see https://github.blog/2020-12-15-token-authentication_git push remote: support for password authentication was removed on august 1