Springboot上传文件&显示进度条

Springboot上传文件&显示进度条StepOne引入依赖<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version></dependency&…

大家好,又见面了,我是你们的朋友全栈君。

Springboot上传文件&显示进度条

 

Step One 引入依赖

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.4</version>
</dependency>

 

Step Two 配置文件解析对象

@Bean(name="multipartResolver")
public MultipartResolver multipartResolver(){
	return new CommonsMultipartResolver();
}

 

Step Three  jsp兼样式

<style type="text/css">
#progressBar {
	width: 300px;
	height: 20px;
	border: 1px #EEE solid;
}

#progress {
	width: 0%;
	height: 20px;
	background-color: lime;
}

.form {
	margin: 10px 345px;
}
</style>

<body>
	<div class="modal-body form ">
		<form id="dialogForm" class="form-horizontal">
			<div class="form-group">
				<label class="col-md-3 col-sm-3  col-xs-3 control-label">版本号:
				</label>
				<div class="col-md-7 col-sm-7  col-xs-7">
					<input type="text" class="form-control " placeholder="请输入版本号"
						id="version">
				</div>
			</div>
			<div class="form-group">
				<label class="col-md-3 col-sm-3 col-xs-3 control-label">部门:
				</label>
				<div class="col-md-7 col-sm-7  col-xs-7">
					<input type="file" name="file" id="file" onchange="upload()">
				</div>
			</div>
			<div class="form-group">
				<label class="col-md-3 col-sm-3  col-xs-3 control-label">上传进度:
				</label>
				<div class="col-md-7 col-sm-7  col-xs-7">
					<!--进度条部分(默认隐藏)-->
					<div class="progress-body">
						<span style="display: inline-block; text-align: right"></span>
						<progress></progress>
						<percentage>0%</percentage>
					</div>
				</div>
			</div>
			<div class="form-group">
				<label class="col-md-3 col-sm-3  col-xs-3 control-label">版本修改内容:
				</label>
				<div class="col-md-7 col-sm-7  col-xs-7">
					<textarea rows="3" cols="47" id="description"></textarea>
				</div>
			</div>
		</form>
		<div class="modal-footer">
			<button type="button" class="btn blue" id="addBtn"
				style="background: #11C2EE; color: #fff">提交</button>
		</div>
	</div>

	<input type="text" hidden="true" id="appUrl">
</body>

Step four  js(需引入jquery)

function upload() {
		// 验证文件内容
		var file = $("#file")[0].files[0];
		if (!file.name.endWith(".apk")) {
			alert("请选择.apk文件");
			return;
		}
		// 上传
		doIt()
	}

	function doIt() {
		var formData = new FormData();
		formData.append("file", $("#file")[0].files[0]);
		$.ajax({
			contentType : "multipart/form-data",
			url : "/mote/app/upload.action",
			type : "POST",
			data : formData,
			processData : false, // 告诉jQuery不要去处理发送的数据 
			contentType : false, // 告诉jQuery不要去设置Content-Type请求头 
			success : function(data) {
				$("#appUrl").val(data); // 保存文件路径
			},
			xhr : function() {
				var xhr = $.ajaxSettings.xhr();
				if (xhr.upload) {
					//处理进度条的事件
					xhr.upload.addEventListener("progress", progressHandle,
							false);
					//加载完成的事件 
					xhr.addEventListener("load", completeHandle, false);
					//加载出错的事件 
					xhr.addEventListener("error", failedHandle, false);
					return xhr;
				}
			}
		});
	}

	//进度条更新 
	function progressHandle(e) {
		$('.progress-body progress').attr({
			value : e.loaded,
			max : e.total
		});
		var percent = e.loaded / e.total * 100;
		$('.progress-body percentage').html(percent.toFixed(2) + "%");
	};
	//上传完成处理函数 
	function completeHandle(e) {
		console.log("上传完成");
	};
	//上传出错处理函数 
	function failedHandle(e) {
		console.log("上传失败");
	};

	String.prototype.endWith = function(endStr) {
		var d = this.length - endStr.length;
		return (d >= 0 && this.lastIndexOf(endStr) == d)
	}

	// 添加内容
	$("#addBtn").click(function() {
		var params = {
			version : $("#version").val(),
			url : $("#appUrl").val(),
			description : $("#description").val()
		}

		$.ajax({
			url : "/mote/app/add.action",
			data : JSON.stringify(params),
			type : "POST",
			contentType : "application/json",
			success : function(data) {
				if (data == -1)
					alert("该版本已存在")
				if (data == 1)
					alert("上传成功")
			},
			error : function(data) {
				alert("服务器繁忙");
			}
		});

	});

 

Step five Controller代码

@PostMapping("/upload")
	@ResponseBody
	public ResponseEntity<String> fileUpload(
			@RequestParam("file") MultipartFile file, HttpServletRequest request) {

		// 判断文件是否有内容
		if (file.isEmpty())
			return new ResponseEntity<String>(Constant.isEmpty, HttpStatus.OK);

		try {
			// 获取文件名称
			String fileName = file.getOriginalFilename();

			// 定义上传路径
			// System.getProperty("file.separator") 根据系统获取分隔符
			String path = request.getSession().getServletContext()
					.getRealPath("");
			String contextPath = request.getContextPath();
			path = path.replace(contextPath.substring(1), "") + "apkDir"
					+ System.getProperty("file.separator") + fileName;

			// 根据文件的全路径名字(含路径、后缀),new一个File对象dest
			File dest = new File(path);
			// 如果该文件的上级文件夹不存在,则创建
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}

			// 向指定路径写入文件
			file.transferTo(dest);
			// 返回文件访问路径
			String url = request.getScheme() + "://" + request.getServerName()
					+ ":" + request.getServerPort() + "/apkDir/" + fileName;
			return new ResponseEntity<String>(url, HttpStatus.OK);
		} catch (Exception e) {
			log.info("文件上传失败" + e);
		}
		return new ResponseEntity<String>(Constant.upload_fail, HttpStatus.OK);
	}

	@PostMapping("/add")
	@ResponseBody
	public ResponseEntity<Integer> addV(@RequestBody App app) {
		try {

			// 验证版本是否存在
			int count = uploadService.getApp(app.getVersion());
			if (count > Constant.ZERO)
				return new ResponseEntity<Integer>(Constant.ERROR,
						HttpStatus.OK);
			// 设置时间
			app.setTimestamp(new Date().getTime());

			int numb = uploadService.addV(app);
			if (numb == Constant.ONE)
				return new ResponseEntity<Integer>(Constant.OK, HttpStatus.OK);

		} catch (Exception e) {
			log.info("添加app失败!!!" + e);
		}
		return new ResponseEntity<Integer>(HttpStatus.INTERNAL_SERVER_ERROR);
	}

附录 Constant类

public class Constant {
	
	public static final int OK = 1;
	
	public static final int ERROR = -1;
	
	public static final int ZERO = 0;
	
	public static final int ONE = 1;
	
	public static final int TWO = 2;
	
	public static final int THREE = 3;
	
	public static final String isEmpty = "0";
	
	public static final String isExit = "-2";
	
	public static final String upload_fail = "-1";

}

记录用的 写的不是很用心,有问题的请留言,谢谢

 

 

 

 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/137674.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 插头DP小结_dp插头接线标准

    插头DP小结_dp插头接线标准插头DP一般都是棋盘模型,找路径或者环路最值或者方案数。插头:说白了就是两个联通的格子,一个走向另一个,那么这里就有一个插头。轮廓线:DP逐格DP,那么轮廓线可以分开DP过的格子和未DP的格子。轮廓线的长度明显是m+1。插头垂直于轮廓线。转移:轮廓线在换行的时候要位移,这个画画图就出来了。然后具体问题具体讨论。比如任意多个环路,不考虑方向,那么就是eatthetrees,用最

    2025年7月5日
    3
  • Eclipse中建多层级包时出现的问题「建议收藏」

    Eclipse中建多层级包时出现的问题「建议收藏」最近一直在学习idea的使用,好久没有用Eclipse了,今天想试着写一个功能,但是在Eclipse中创建包时出现问题了。创建的包都成为平级了。那么Eclipse中如何创建多层包呢?解决方案:    方法一:         1)先在src文件夹下创建com包,在com包里面创建一个类,例如:点击Finish就会出现如下:    2)以此类推建想要建的包,在删除之前的Test类即可。以下是我的效果…

    2022年6月13日
    33
  • phpstorm 激活码【注册码】

    phpstorm 激活码【注册码】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月20日
    39
  • pycharm pyinstaller打包exe_pip安装第三方库失败

    pycharm pyinstaller打包exe_pip安装第三方库失败1.安装时打开AnacondaPrompt,然后cdD:\Anaconda3\pkgs打开路径,输入安装命令:pipinstallPyInstaller。最后输入piplist查看2.调出terminal终端,输入命令例如pyinstaller-F-wvipvideoplay2.py点击回车如图:输入指定命令后会在当前目录下生产dist文件夹,dist文件夹下为生成的exe文件参数说明:-F:将所有库文件打包成一个exe-w:隐藏黑色控制台窗口如果不加-F参数会生成很多文

    2022年8月27日
    6
  • Pytest(13)命令行参数–tb的使用

    Pytest(13)命令行参数–tb的使用前言pytest使用命令行执行用例的时候,有些用例执行失败的时候,屏幕上会出现一大堆的报错内容,不方便快速查看是哪些用例失败。–tb=style参数可以设置报错的时候回溯打印内容,可以设置参

    2022年7月29日
    7
  • 光功率 博科交换机_博科光纤交换机zone划分命令方法「建议收藏」

    光功率 博科交换机_博科光纤交换机zone划分命令方法「建议收藏」博科光纤交换机zone划分命令方法Brocade(博科)交换机为例,记录其划分命令和划分方法:连接交换机:可通过串口或网线从IE进入,默认IP  10.77.77.77,255.255.255.0创建ZONE有两种方式:一是通过交换机port号,二是通过主机和存储的WWN号 (单个硬盘没有WWN号,存储整体才有一个)命令:查看当前zone状况:zoneshow删除zone:zonedele…

    2022年5月22日
    40

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号