springboot⾥使⽤websocket实现⽂件上传并且显⽰进度⾸先,我们清晰⼀下思路
1)先实现⽂件上传,我们应该清楚,⽂件上传和进度⾛的是两条路线,即异步;
2)再使⽤⽂件上传解析器去获取⽂件进度信息,这个信息是保存在⼀个session域⾥的,会被实时刷新;
3)websocket定时遍历,实现点对点发送上传进度信息;
很简单,就这三步
接下来开始实现
所需的maven依赖
<!--⽂件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!-- webscoket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
实现第⼀步和第⼆步
后台主要有下⾯⼏个类
1.FileuploadClass ⽂件上传配置信息,继承了CommonsMultipartResolver
import org.apachemons.fileupload.FileUpload;
import org.apachemons.fileupload.FileItem;
import org.apachemons.fileupload.FileUploadBase;
import org.apachemons.fileupload.FileUploadException;
jsp用什么前端框架import org.apachemons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipartmons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @ClassName FileUpload
* @Description TODO
* @Author fzj
* @Date 2020-3-26 13:21
* @Version 1.0.0
**/
public class FileUploadClass extends CommonsMultipartResolver {
private UploadProgressListener progressListener = new UploadProgressListener();
public void setFileUploadProgressListener(
UploadProgressListener progressListener) {
this.progressListener = progressListener;
}
public MultipartParsingResult parseRequest(HttpServletRequest request)
throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
progressListener.Session());
fileUpload.setProgressListener(progressListener);
try {
@SuppressWarnings("unchecked")
List<FileItem> fileItems = ((ServletFileUpload) fileUpload)
.parseRequest(request);
return parseFileItems(fileItems, encoding);
} catch (FileUploadBase.SizeLimitExceededException ex) {
throw new SizeMax(),
ex);
} catch (FileUploadException ex) {
throw new MultipartException(
"Could not parse multipart servlet request", ex);
}
}
}
2.FileUploadConfig 配置类 ⽤于springboot项⽬加载时注⼊⽂件上传配置⽂件的bean
import t.annotation.Bean;
import t.annotation.Configuration;
/**
* @ClassName FileUPDConfig
* @Description TODO
* @Author fzj
* @Date 2020-4-1 8:19
* @Version 1.0.0
**/
@Configuration
public class FileUploadConfig {
@Bean
public FileUploadClass fileUploadConfig(){
return new FileUploadClass();
}
}
3.UploadProgressListener ⽂件上传状态 实现了ProgressListener
import del.ProgressEntity;
import org.apachemons.fileupload.ProgressListener;
import javax.servlet.http.HttpSession;
/**
* @ClassName UploadProgressListener
* @Description TODO
* @Author fzj
* @Date 2020-4-1 8:15
* @Version 1.0.0
**/
public class UploadProgressListener implements ProgressListener {
private HttpSession session;
public void setSession(HttpSession session) {
this.session = session;
ProgressEntity status = new ProgressEntity();// 保存上传状态
session.setAttribute("status", status);
}
@Override
public void update(long bytesRead, long contentLength, int items) {
ProgressEntity status = (ProgressEntity) Attribute("status");
status.setBytesRead(bytesRead);// 已读取数据长度
status.setContentLength(contentLength);// ⽂件总长度
status.setItems(items);// 正在保存第⼏个⽂件
}
}
4.ProgressEntity 进度实体类
/**
* @ClassName ProgressEntity
* @Description TODO
* @Author fzj
* @Date 2020-3-26 12:56
* @Version 1.0.0
**/
public class ProgressEntity {
private long bytesRead;
private long contentLength;
private long items;
private long startTime = System.currentTimeMillis(); // 开始上传时间,⽤于计算上传速率
public ProgressEntity() {
}
public long getBytesRead() {
return bytesRead;
}
public void setBytesRead(long bytesRead) {
this.bytesRead = bytesRead;
}
public long getContentLength() {
return contentLength;
}
public void setContentLength(long contentLength) {
}
public long getItems() {
return items;
}
public void setItems(long items) {
this.items = items;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
}
5.FileUploadCommonTool ⽂件上传通⽤操作类
import del.ProgressEntity;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
/**
* @ClassName FileUploadCommonTool
* @Description TODO
* @Author fzj
* @Date 2020-4-9 10:05
* @Version 1.0.0
**/
public class FileUploadCommonTool {
public static Map<String, Object> upload(MultipartFile Fdata, String Sid, HttpServletRequest request) {
String infilename = OriginalFilename();
String endstring = infilename.substring(infilename.lastIndexOf("."));
//这⾥写⾃⼰的⽂件名和⽂件夹即可
String fromstring = SystemDateFormat.SdfForTimeString.format(new Date());
String path = "C:\\Users\\Administrator\\Desktop\\_11_4_1临时⽂件夹\\20200326\\" + fromstring + endstring; Map<String, Object> map = new HashMap<>(1);
InputStream fis = null;
FileOutputStream fos = null;
try {
File fileo = new File(path);
if (!ists()) {
}
fos = new FileOutputStream(fileo);
fis = InputStream();
byte[] bytes = new byte[1024];
int aa = 0;
while (true) {
aa = ad(bytes, 0, bytes.length);
if (aa == -1) {
break;
}
fos.write(bytes, 0, aa);
}
} catch (Exception e) {
map.put("issuccess", false);
} finally {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
public static Map<String, Object> getUploadInfo(HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
ProgressEntity status = (ProgressEntity) Session(true)
.getAttribute("status");// 从session中读取上传信息
if (status == null) {
result.put("error", "没发现上传⽂件!");
return result;
}
long startTime = StartTime(); // 上传开始时间
long currentTime = System.currentTimeMillis(); // 现在时间
long time = (currentTime - startTime) / 1000 + 1;// 已经传顺的时间单位:s
double velocity = BytesRead() / time; // 传输速度:byte/s
double totalTime = ContentLength() / velocity; // 估计总时间
double timeLeft = totalTime - time; // 估计剩余时间
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论