如何使用Springboot实现文件上传和下载,并为其添加实时进度条的功能
文件上传和下载是Web开发中非常基础的功能,但在实际开发中,我们经常需要实时显示文件上传或下载的进度。这篇文章将介绍如何使用Springboot实现文件上传和下载,并为其添加实时进度条的功能。
文件上传
添加Maven依赖项
首先,我们需要添加以下Maven依赖项:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version>
</dependency>
其中,spring-boot-starter-web是Spring Boot提供的用于构建Web应用程序的依赖项之一,commons-fileupload是一个流行的Java文件上传库。
创建HTML表单
接下来,我们需要创建一个HTML表单来提交文件。在这个表单中,我们可以使用元素来选择要上传的文件,并使用元素来提交表单。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>File Upload</title>
</head>
<body><form action="/upload" method="post" enctype="multipart/form-data"><input type="file" name="file"/><br/><input type="submit" value="Upload"/></form>
</body>
</html>
在这个表单中,我们将表单的action属性设置为"/upload",这是我们将要处理上传请求的URL。
实现文件上传
在Springboot中,可以使用org.springframework.web.multipart.MultipartFile类来处理上传的文件。我们可以编写一个Controller来接收并处理上传的文件:
@RestController
public class UploadController {@PostMapping("/upload")public String upload(@RequestParam("file") MultipartFile file) throws IOException {// do something with the filereturn "success";}
}
在上面的代码中,我们使用@RequestParam注解来指定文件上传的参数名,并将文件保存到磁盘或者进行其他操作。最后,我们返回一个简单的字符串作为响应内容。
添加进度条
为了实现上传进度条功能,我们需要使用JavaScript和Ajax来实现。具体来说,我们可以使用XMLHttpRequest对象来发送异步请求,并在上传过程中实时更新进度条。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>File Upload</title><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script><script>$(function () {$("form").submit(function (event) {event.preventDefault();var formData = new FormData($(this)[0]);$.ajax({xhr: function () {var xhr = new window.XMLHttpRequest();xhr.upload.addEventListener("progress", function (evt) {if (evt.lengthComputable) {var percentComplete = evt.loaded / evt.total;console.log(percentComplete);$("#progress").css("width", percentComplete * 100 + "%");}}, false);xhr.addEventListener("progress", function (evt) {if (evt.lengthComputable) {var percentComplete = evt.loaded / evt.total;console.log(percentComplete);$("#progress").css("width", percentComplete * 100 + "%");}}, false);return xhr;},type: "POST",url: "/upload",data: formData,processData: false,contentType: false,success: function (data) {alert("Upload complete!");}});});});</script>
</head>
<body>
<form><input type="file" name="file"/><br/><button type="submit">Upload</button>
</form>
<div style="background-color: #ddd; height: 20px; width: 0%;" id="progress"></div>
</body>
</html>
在上面的代码中,我们使用了jQuery来发送XHR请求,并在上传过程中更新进度条。具体来说,我们为xhr.upload和xhr对象添加了progress事件处理程序,以便在上传文件时实时更新进度条。
文件下载
实现文件下载
要实现文件下载,我们需要编写一个Controller来处理下载请求,并使用org.springframework.core.io.Resource类将文件作为响应内容返回给客户端。
@RestController
public class DownloadController {@GetMapping("/download")public ResponseEntity<Resource> download() throws IOException {Resource file = new FileSystemResource("/path/to/file");HttpHeaders headers = new HttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFilename());return ResponseEntity.ok().headers(headers).contentLength(file.contentLength()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(file.getInputStream()));}
}
在上面的代码中,我们使用@GetMapping注解来指定处理下载请求的URL,并使用org.springframework.core.io.Resource类来读取文件内容。最后,我们将文件作为响应内容返回给客户端。
添加进度条
添加下载进度条功能与上传进度条类似,我们仍然可以使用XMLHttpRequest对象和JavaScript来实现。具体来说,我们可以向Controller发送一个异步请求,并在下载过程中实时更新进度条。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>File Download</title><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script><script>$(function () {$("#download").click(function (event) {event.preventDefault();var xhr = new XMLHttpRequest();xhr.open("GET", "/download", true);xhr.responseType = "blob";xhr.onload = function () {if (xhr.status === 200) {var contentType = xhr.getResponseHeader("Content-Type");var contentDisposition = xhr.getResponseHeader("Content-Disposition");var blob = new Blob([xhr.response], {type: contentType});var link = document.createElement("a");link.href = window.URL.createObjectURL(blob);link.download = contentDisposition.split("=")[1];link.click();}};xhr.addEventListener("progress", function (evt) {if (evt.lengthComputable) {var percentComplete = evt.loaded / evt.total;console.log(percentComplete);$("#progress").css("width", percentComplete * 100 + "%");}}, false);xhr.send();});});</script>
</head>
<body>
<button id="download">Download</button>
<div style="background-color: #ddd; height: 20px; width: 0%;" id="progress"></div>
</body>
</html>
在上面的代码中,我们使用了jQuery来发送XHR请求,并在下载过程中更新进度条。具体来说,我们为xhr对象添加了progress事件处理程序,以便在文件下载时实时更新进度条。
结论
本文介绍了如何使用Springboot实现文件上传和下载,并为其添加实时进度条的功能。在上传和下载文件时,我们使用了XMLHttpRequest对象和JavaScript来实现实时进度条。这个功能可以帮助用户更好地了解文件上传和下载的进度,提升用户体验。