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";

}

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

 

 

 

 

 

 

 

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中实现文件上传进度条可以使用一些现有的库或自定义解决方案。以下是一个简单的示例,展示了如何使用Spring Boot和AJAX实现文件上传进度条功能。 首先,确保你的Spring Boot项目中已经添加了以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> ``` 接下来,创建一个Controller来处理文件上传的请求: ```java import org.apache.commons.fileupload.ProgressListener;import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; @Controller public class FileUploadController { @Value("${upload.path}") private String uploadPath; // 文件上传路径 @PostMapping("/upload") @ResponseBody public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) { Map<String, Object> result = new HashMap<>(); if (file.isEmpty()) { result.put("success", false); result.put("message", "请选择文件"); return result; } try { // 创建文件上传进度监听器 ProgressListener progressListener = new CustomProgressListener(request.getSession()); // 创建文件上传处理器 ServletFileUpload upload = new ServletFileUpload(); upload.setProgressListener(progressListener); // 执行文件上传 String filename = file.getOriginalFilename(); file.transferTo(new File(uploadPath + File.separator + filename)); result.put("success", true); result.put("message", "文件上传成功"); } catch (IOException e) { result.put("success", false); result.put("message", "文件上传失败"); } return result; } } ``` 在上面的代码中,我们使用`@RequestParam`注解来接收上传的文件,并通过`MultipartFile`类型的参数接收。在文件上传过程中,我们创建了一个自定义的进度监听器`CustomProgressListener`,可以用来获取上传进度信息。 接下来,我们需要实现进度监听器: ```java import org.apache.commons.fileupload.ProgressListener; import javax.servlet.http.HttpSession; public class CustomProgressListener implements ProgressListener { private HttpSession session; public CustomProgressListener(HttpSession session) { this.session = session; } @Override public void update(long bytesRead, long contentLength, int items) { // 计算上传的百分比 double percent = (bytesRead * 100.0) / contentLength; // 将进度信息存储在session中 session.setAttribute("uploadProgress", percent); } } ``` 在进度监听器中,我们计算了上传的百分比,并将结果存储在`HttpSession`中,以便在前端页面中获取。 最后,在前端页面中使用AJAX轮询来获取上传进度: ```javascript function uploadFile() { var formData = new FormData(); var fileInput = document.getElementById("fileInput"); formData.append("file", fileInput.files[0]); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(event) { if (event.lengthComputable) { var percentComplete = (event.loaded / event.total) * 100; console.log(percentComplete + "%"); } }, false); xhr.open("POST", "/upload"); xhr.send(formData); } ``` 以上代码创建了一个XMLHttpRequest对象,并通过监听`progress`事件来获取上传进度信息,然后将信息打印到控制台。 这样,当你执行`uploadFile()`函数时,就可以实时获取文件上传的进度了。 这只是一个简单的示例,你可以根据实际需求进行扩展和优化。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值